簡體   English   中英

如何檢查URL是否存在 - 錯誤404? (使用php)

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

如何檢查URL是否存在 - 錯誤404? (使用php)

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

如果你有allow_url_fopen ,你可以這樣做:

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

雖然嚴格來說,這不會僅對404錯誤返回false。 可以使用流上下文來獲取該信息,但更好的選擇是使用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);

最簡單的檢查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';}

?>

你可以使用curl這是一個PHP庫。 使用curl,您可以查詢頁面,然后檢查名為的錯誤代碼:

CURLE_HTTP_RETURNED_ERROR (22)

如果CURLOPT_FAILONERROR設置為TRUE且HTTP服務器返回> = 400的錯誤代碼,則返回此值。

來自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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM