I dont understand when I echo $httpCode I always get 0, I was expecting 404 when I change $html_brand into a broken url. Is there anything that I miss or do not know of? Thanks.
//check if url exist
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $html_brand);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 404) {
echo "The Web Page Cannot Be Found";
return;
}
curl_close($ch);
Another reason for PHP to return http code 0 is timeout. In my case, I had the following configuration:
curl_setopt($http, CURLOPT_TIMEOUT_MS,500);
It turned out that the request to the endpoint I was pointing to always took more than 500 ms, always timing out and always returning http code 0.
If you remove this setting (CURLOPT_TIMEOUT_MS) or put a higher value (in my case 5000), you'll get the actual http code, in my case a 200 (as expected).
What is the exact contents you are passing into $html_brand?
If it is has an invalid URL syntax, you will very likely get the HTTP code 0.
If you're using selinux it might be because of security restrictions. Try setting this as root:
# setsebool -P httpd_can_network_connect on
Like said here and below, a failed request (i.e. the server is not found) returns false, no HTTP status code, since a reply has never been received.
Call curl_error()
.
check the curl_error after the curl_getinfo to find out the hidden errors.
if(curl_errno($ch)){
echo 'Curl error: ' . curl_error($ch);
}
Try this after curl_exec to see what's the problem:
print curl_error($ch);
If it's print something like 'malformed' then check your URL format.
Try this:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
I had same problem and in my case this was because curl_exec function is disabled in php.ini. Check for logs:
PHP Warning: curl_exec() has been disabled for security reasons in /var/www/***/html/test.php on line 18
Solution is remove curl_exec from disabled functions in php.ini on server configuration file.
Source: Stackoverflow.com