What is the best way in PHP to see if an URL exists (Url is typed by user, so may not be in the correct URL format). I have looked through the internet and this is rather difficult to find.
Asked
Active
Viewed 457 times
2
-
Do you want to check the url in valid format ? – Vinod VT Apr 21 '14 at 05:15
-
I want to check if the format is correct and then check if the url actually exists - can this be done by using one php function or should I use two seperately? – Apr 21 '14 at 05:16
-
1IMO you'd be better off just tested the url regardless. If it fails, one potential fail reason would be because it was a malformed url – Rogue Apr 21 '14 at 05:17
-
Maybe `parse_url` or `filter_var` w/`FILTER_VALIDATE_URL` if you want to check for valid url/validate url and/or check with something like `curl` if the link is valid/live. – Class Apr 21 '14 at 05:20
2 Answers
1
Here you need only to check the URL is exist. Only valid URL format is exist. Try this code,
<?php
$url = 'http://www.example.com';
$array = get_headers($url);
$string = $array[0];
if((strpos($string,"200"))||(strpos($string,"302")))
{
echo 'url exists';
}
else
{
echo 'url does not exist';
}
?>

Vinod VT
- 6,946
- 11
- 51
- 75
-
Theres more than just `200` for valid url's. Also `get_headers` returns false on error. – Class Apr 21 '14 at 05:31
-
I tested this and it does not seem to work (even with `http://www.facebook.com`) EDIT: it needs to have the https apparantly. – Apr 21 '14 at 05:53
-
@user3353408 thats why I said `200` isn't always valid and you are getting `302` code which is `Found` which is essentially redirect code because there is a `https` version. If you were to use `curl` you could use a 'follow redirect' to check if the end page is valid. – Class Apr 21 '14 at 06:01
-
0
I would look into doing an AJAX get request to the URL they typed and check if an http error message (such as 404) is returned.
Jquery makes it pretty simple to do ajax calls, and actually might not need to test for a 404 message, it will just fail and run the error function. https://api.jquery.com/jQuery.ajax/

Andrew
- 18,680
- 13
- 103
- 118