简体   繁体   中英

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

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

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

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);

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';}

?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM