2014-12-06 125 views
1

我想找到一种方法来处理任何4xx和5xx错误状态代码抛出像Apache 404错误的URL。我只想在服务器没有抛出错误状态码的情况下执行if语句的内容。PHP的URL错误处理

使用以下if语句,似乎即使未找到托管内容并抛出Apache 404错误,它仍然运行if语句的内容。

if (@fopen('http://example','r')){ 
      use resource 
} 
else{ 
use other resources 
} 

有没有更好的方法来确保网址在运行之前可用?

编辑: 我不能在这种情况下使用卷曲。

谢谢

+0

使用卷曲,使HEAD电话吗? – 2014-12-06 03:47:33

+0

有没有这样的事情作为错误,只有状态代码需要url返回。 – Yang 2014-12-06 03:47:34

+0

我不能使用卷曲,我希望我可以。我的印象是,4xx和5xx状态码称为错误状态码。对不起,我应该更清楚。 – bakingsoda 2014-12-06 03:53:20

回答

0
$headers = get_headers($url, 1); 
    if ($headers[0] == 'HTTP/1.1 200 OK') {//no error status codes thrown by the server 
    $data = file_get_contents($url); 
    //Do something 
    } 
0

使用此。

$headers = @get_headers($url, 1); 
    if ($headers[0] == 'HTTP/1.1 200 OK') { 
    //valid 
    } 
    if($headers[0] == 'HTTP/1.1 404 Not Found') { 
    // not found 
    } 
    if ($headers[0] == 'HTTP/1.1 301 Moved Permanently') { 
    //moved or redirect page 
    } 

get_headers()手册:http://php.net/manual/en/function.get-headers.php