Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a URI exists?

Tags:

php

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.

like image 444
ajsie Avatar asked Jan 27 '26 20:01

ajsie


1 Answers

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);
like image 172
Progman Avatar answered Jan 29 '26 10:01

Progman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!