我需要創建一個函數,該函數在URL可用或有效時返回。確定PHP中是否存在URL的最快方法是什麼?
我目前使用類似以下內容來確定有效的URL:
static public function urlExists($url)
{
$fp = @fopen($url, 'r');
if($fp)
{
return true;
}
return false;
}
看起來會有更快的東西,或許真的只是抓取該網頁的頁眉或東西。
我需要創建一個函數,該函數在URL可用或有效時返回。確定PHP中是否存在URL的最快方法是什麼?
我目前使用類似以下內容來確定有效的URL:
static public function urlExists($url)
{
$fp = @fopen($url, 'r');
if($fp)
{
return true;
}
return false;
}
看起來會有更快的東西,或許真的只是抓取該網頁的頁眉或東西。
你可以檢查http status code。
這裏是一個代碼,你可以使用它來檢查一個url返回2xx或3xx http代碼以確保url的工作。
<?php
$url = "http://stackoverflow.com/questions/1122845";
function urlOK($url)
{
$url_data = parse_url ($url);
if (!$url_data) return FALSE;
$errno="";
$errstr="";
$fp=0;
$fp=fsockopen($url_data['host'],80,$errno,$errstr,30);
if($fp===0) return FALSE;
$path ='';
if (isset($url_data['path'])) $path .= $url_data['path'];
if (isset($url_data['query'])) $path .= '?' .$url_data['query'];
$out="GET /$path HTTP/1.1\r\n";
$out.="Host: {$url_data['host']}\r\n";
$out.="Connection: Close\r\n\r\n";
fwrite($fp,$out);
$content=fgets($fp);
$code=trim(substr($content,9,4)); //get http code
fclose($fp);
// if http code is 2xx or 3xx url should work
return ($code[0] == 2 || $code[0] == 3) ? TRUE : FALSE;
}
echo $url;
if (urlOK($url)) echo " is a working URL";
else echo " is a bad URL";
?>
希望這有助於!
您可能會被限制爲發送某種類型的HTTP請求。然後你可以檢查HTTP狀態碼。
請務必只發送一個「HEAD」請求,該請求不會撤回所有內容。這應該足夠重量輕。
您可以使用捲曲如下:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true); // set to HEAD request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // don't output the response
curl_exec($ch);
$valid = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200;
curl_close($ch);
還檢查2xx和3xx,因爲它可能是301永久移動或另一個http代碼,這意味着該網址的作品。 – 2009-07-14 03:55:05