I have the following code in one of my Wordpress page templates:
$url = "https://xxxxxxxxxxxxxxx/";
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
$args = [
"ctype" => sanitize_text_field($_GET['ctype']),
];
if ($args['ctype'] == "test") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, wp_json_encode($args));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
// Check HTTP status code
if (!curl_errno($ch)) {
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "HTTP Code: $http_code";
} else {
echo 'cURL Error: ' . curl_error($ch) . "\n";
}
curl_close($ch);
}
My code is executing extremely slow. I initially had CURLOPT_TIMEOUT set to 10. This was waiting for 10 seconds for the script to execute. Then when I switch it to 2, it was running quite fast but I think there is still a bigger problem.
In the if (!curl_errno($ch))
statement, it always goes to the else
statement and echoes out cURL Error: Operation timed out after 2001 milliseconds with 0 bytes received. I don't really understand why it is always going into the else
statement.
I have tried other cURL directives such as:
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($ch, CURLOPT_SSL_SESSIONID_CACHE, true);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 3600);
curl_setopt($ch, CURLOPT_TCP_FASTOPEN, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
but none of these seemed to have any effect.
Detailed timings based on curl_setopt($ch, CURLOPT_TIMEOUT, 10)
:
CURLINFO_TOTAL_TIME: 10s
CURLINFO_NAMELOOKUP_TIME: 0.001s
CURLINFO_CONNECT_TIME: 0.156s
CURLINFO_PRETRANSFER_TIME: 0.473s
CURLINFO_STARTTRANSFER_TIME: 0s
CURLINFO_HEADER_OUT: nothing returned
wp_remote_post()
but it was giving a similar issue, so I resorted to PHP cURL. I've updated my post above to add some additional details about the timings.