2010-03-12 78 views
3

如何檢查PHP是否存在URI?檢查一個URI是否存在?

我想它會返回一個錯誤代碼,我可以在使用file_get_contents之前檢查它,因爲如果我在不存在的鏈接上使用file_get_contents,它會給我一個錯誤。

+2

這個問題怎麼回答不了? – Pointy 2010-03-12 15:34:45

+2

它不會返回我一個錯誤代碼,我可以做一個if語句。它給了我一個錯誤頁面。 – ajsie 2010-03-12 15:37:31

回答

2

嘗試功能array get_headers($url, [, int $format = 0 ]),它應該返回false失敗 - 否則,您可以假設uri存在,因爲web服務器爲您提供了標題信息。

我希望該功能使用HTTP HEAD請求而不是GET,這會導致比上述fopen解決方案少得多的流量。

3

試着這麼做:

if ($_REQUEST[url] != "") { 
    $result = 1; 
    if (! ereg("^https?://",$_REQUEST[url])) { 
     $status = "This demo requires a fully qualified http:// URL"; 
    } else { 
     if (@fopen($_REQUEST[url],"r")) { 
      $status = "This URL s readable"; 
     } else { 
      $status = "This URL is not readable"; 
     } 
    } 
} else { 
    $result = 0; 
    $status = "no URL entered (yet)"; 
} 

然後事後你可以使用調用這個函數:

if ($result != 0) { 
    print "Checking URL <b>".htmlspecialchars($_REQUEST[url])."</b><br />"; 
} 
print "$status"; 
+0

ereg()在PHP 5.3中被棄用,並且將被PHP 6刪除。您應該使用preg_match()來代替。 – 2010-03-12 16:16:13

+0

O,對。感謝您的領導! – lugte098 2010-03-22 08:27:48

4

您可以發送CURL請求的URI/URL。根據協議,您可以檢查結果。對於HTTP,您應該檢查HTTP狀態碼404。檢查the curl manual on php.net。在某些情況下,您可以使用file_exists()函數。

<?php 
$curl = curl_init('http://www.example.com/'); 
curl_setopt($curl, CURLOPT_NOBODY, true); 
curl_exec($curl); 
$info = curl_getinfo($curl); 
echo $info['http_code']; // gives 200 
curl_close($curl); 

$curl = curl_init('http://www.example.com/notfound'); 
curl_setopt($curl, CURLOPT_NOBODY, true); 
curl_exec($curl); 
$info = curl_getinfo($curl); 
echo $info['http_code']; // gives 404 
curl_close($curl); 
2
try { 
    $fp = @fsockopen($url, 80); 
    if (false === $fp) throw new Exception('URI does not exist'); 
    fclose($fp); 
    // do stuff you want to do it the URI exists 
} catch (Exception $e) { 
    echo $e->getMessage(); 
}