2

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

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

3 Answers 3

8

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);
Sign up to request clarification or add additional context in comments.

3 Comments

@fare You're right, it appears the http wrapper doesn't support static stats. See my edit.
$exists = (@$fp = fopen($url, "r")) !== FALSE; if ($fp) fclose($fp); if ($exists==true) { echo " true"; } elseif ($exists==false) { echo " false"; }
3

The simplest one to check the 404/200 or etc..

<?php
$mylink="http://site.com";
$handler = curl_init($mylink);
curl_setopt($handler,  CURLOPT_RETURNTRANSFER, TRUE);
$re = curl_exec($handler);
$httpcdd = curl_getinfo($handler, CURLINFO_HTTP_CODE);


if ($httpcdd == '404')
     { echo 'it is 404';}
else {echo 'it is not 404';}

?>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.