tags:

views:

31

answers:

2

how to check if a URL exists or not - error 404 ? (using php)

<?php
$url = "http://www.faressoft.org/";
?>
+1  A: 

If you have allow_url_fopen, you can do:

$exists = ($fp = fopen("http://www.faressoft.org/", "r")) !== FALSE;
if ($fp) fclose($fp);

although strictly speaking, this won't return false only for 404 errors. It's possible to use stream contexts to get that information, but a better option is to use the curl extension:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/notfound");
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$is404 = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 404;
curl_close($ch);
Artefacto
it doesn't work !http://www.fahwa.com/check.php?url=http://www.faressoft.org
faressoft
@fare You're right, it appears the http wrapper doesn't support static stats. See my edit.
Artefacto
very good, but how to hide error msg and print false.http://www.fahwa.com/check.php?url=http://www.google.com.sa/anythinghttp://www.fahwa.com/check.php?url=http://www.google.com.sa
faressoft
$exists = (@$fp = fopen($url, "r")) !== FALSE;if ($fp) fclose($fp);if ($exists==true) { echo " true";} elseif ($exists==false) { echo " false";}
faressoft
Thank you very much.
faressoft
A: 

You could use curl which is a PHP library. With curl, you could query the page and then check for the error code called:

CURLE_HTTP_RETURNED_ERROR (22)

This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400.

From the CURL documentation at php.net:

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');

// Execute
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);

// Check if any error occured
if(curl_errno($ch))
{
    echo 'Curl error: ' . curl_error($ch);
}

// Close handle
curl_close($ch);
?>

http://www.php.net/manual/en/function.curl-errno.php

David L Ernstrom