0

I have URL like this "http://example.com/index.php?id=10". How can i check whether this URL exists or not?

EbinPaulose
  • 1,129
  • 3
  • 14
  • 26
  • 1
    You can curl the page or use file_get_contents() function – Dr. Dan Jul 30 '12 at 10:30
  • 2
    How about check if similar questions exists or not in SO...! See this:: http://stackoverflow.com/questions/2280394/check-if-an-url-exists-in-php – Sudhir Bastakoti Jul 30 '12 at 10:33
  • Just to be pedantic. Do you really want to check if it exists? Or if it exists without redirection, or if you are authorized to access it? (it might exist, but you are not allowed access) http://en.wikipedia.org/wiki/List_of_HTTP_status_codes – Mawg says reinstate Monica Jul 30 '12 at 12:18

2 Answers2

1

Use the get_headers function.

$url = 'http://www.example.com';    
$headers = get_headers($url, 1);

if ($headers !== false && substr($headers[0], 9, 3) == 200) {
    echo 'Page exists';
}
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
1

If the website is properly set up, you should get a 200 OK status code if the URL exists and you are allowed to see it. You can check this with curl:

$http = curl_init("http://example.com/index.php?id=10");
curl_exec($http);
$responseCode = curl_getinfo($http, CURLINFO_HTTP_CODE);
if($responseCode == 200)
    //Page exists

Code not tested

Henrik Karlsson
  • 5,559
  • 4
  • 25
  • 42
  • +1 but ... I think you mean "200 OK status code if the URL exists *and you are authorized to access it (etc)*". The OP _says_ he wants to check if it exists (which your code won't correctly check if he is not allowed to access it). Your code answers his question as asked. I just wonder if it is really what he wanted to ask (see http://en.wikipedia.org/wiki/List_of_HTTP_status_codes). – Mawg says reinstate Monica Jul 30 '12 at 12:23
  • ah true, clarifying it in the answer – Henrik Karlsson Jul 30 '12 at 12:26