2010-03-12 73 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(); 
}