[英]how to check if a URL exists or not - error 404 ? (using php)
how to check if a URL exists or not - error 404 ? 如何检查URL是否存在 - 错误404? (using php) (使用php)
<?php
$url = "http://www.faressoft.org/";
?>
If you have allow_url_fopen
, you can do: 如果你有allow_url_fopen
,你可以这样做:
$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. 虽然严格来说,这不会仅对404错误返回false。 It's possible to use stream contexts to get that information, but a better option is to use the curl extension: 可以使用流上下文来获取该信息,但更好的选择是使用curl扩展:
$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.. 最简单的检查404/200等等。
<?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. 你可以使用curl这是一个PHP库。 With curl, you could query the page and then check for the error code called: 使用curl,您可以查询页面,然后检查名为的错误代码:
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. 如果CURLOPT_FAILONERROR设置为TRUE且HTTP服务器返回> = 400的错误代码,则返回此值。
From the CURL documentation at php.net: 来自php.net的CURL文档:
<?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 http://www.php.net/manual/en/function.curl-errno.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.