Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP URL错误处理_Php_Apache_Fopen - Fatal编程技术网

PHP URL错误处理

PHP URL错误处理,php,apache,fopen,Php,Apache,Fopen,我正试图找到一种方法来处理由类似Apache404Error的url抛出的任何4xx和5xx错误状态代码。我只想在服务器没有抛出错误状态代码的情况下执行if语句的内容 使用下面的if语句,似乎即使找不到托管内容并抛出apache404错误,它仍然在运行if语句的内容 if (@fopen('http://example','r')){ use resource } else{ use other resources } 在运行url之前,是否有更好的方法确保url可用

我正试图找到一种方法来处理由类似Apache404Error的url抛出的任何4xx和5xx错误状态代码。我只想在服务器没有抛出错误状态代码的情况下执行if语句的内容

使用下面的if语句,似乎即使找不到托管内容并抛出apache404错误,它仍然在运行if语句的内容

if (@fopen('http://example','r')){
            use resource
}
else{
use other resources
}
在运行url之前,是否有更好的方法确保url可用

编辑: 在这种情况下,我不能使用curl

谢谢你用这个。

  $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()手册:

使用curl并进行HEAD调用?没有错误之类的事情,只有需要返回url的状态代码。我不能使用curl,我希望可以。我的印象是4xx和5xx状态代码,其中称为错误状态代码。对不起,我应该说得更清楚一些。请检查与您的期望相关的。
 $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
  }