cURL question, how to verify if URL is valid

AndyB

Well-known member
I would like to be able to use cURL and have the script determine if the file path is reachable. Here's an example of code that verifies the domain is reachable:

PHP:
<?php

// Create a curl handle to a non-existing location
$ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if (curl_exec($ch) === false) {
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);

?>

This works fine. But if I change the path to something like this:

http://www.google.com/path_to_invalid_image.jpg

it still shows as a valid path.

So how would I modify the code to show an error if the path to a file is invalid?
 
Last edited:
I'm not sure how to do it with cURL actually.

I tend to use the XenForo_Helper_Http class.

Incredibly easy to use.

But in relation to the code you've already written, I think you need this:

PHP:
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

Obviously if $httpCode contains 404, 403 etc. then you can throw an error.
 
To do it with curl, add
curl_setopt($ch, CURLOPT_FAILONERROR, true);

If you just want to make sure the URL exists, you should be also doing a HEAD request instead of a GET to avoid transferring the data.

For that, see the option CURL_NOBODY.
 
Hi Ken,

Thank you kindly for your information, works perfectly.

PHP:
<?php

// Create a curl handle to a non-existing location
$ch = curl_init('http://www.google.com/path_to_invalid_image.jpg');

curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_NOBODY, true);

if (curl_exec($ch) === false) {
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);

?>
 
Top Bottom