How do I check if a URI exists with PHP?
I guess it will return an error code and I can check it before I use file_get_contents, because if I use file_get_contents on a link that doesn't exist, it gives me an error.
You can send a CURL request to the uri/url. Depending on the protocol you can check the result. For HTTP you should check for the HTTP status code 404. Check the curl manual on php.net. In some cases you can use the file_exists() function.
<?php
$curl = curl_init('http://www.example.com/');
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_exec($curl);
$info = curl_getinfo($curl);
echo $info['http_code']; // gives 200
curl_close($curl);
$curl = curl_init('http://www.example.com/notfound');
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_exec($curl);
$info = curl_getinfo($curl);
echo $info['http_code']; // gives 404
curl_close($curl);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With