如何在使用错误代理的file_get_contents时处理500内部服务器错误


How to handle 500 internal server error when using file_get_contents with a wrong proxy?

如果我在PHP中使用错误的代理运行此代码,我会得到500内部服务器错误。如何处理并继续执行?

$opts = array(
          'http'=>array(
            'method'=>"GET",
            'proxy' => 'tcp://100.100.100.100:80' //a wrong proxy
          )
);
$context = stream_context_create($opts);
$file = file_get_contents('http://ifconfig.me/ip', false, $context);

我想你说"handle"是指两件事:

  1. 如果脚本连接到"错误"的代理,它将等待很长时间来建立连接,直到超时。脚本应该设置一个较低的超时时间,这样用户就不会永远等待
  2. 如果在访问外部资源的过程中发生错误,不要死亡或显示难看的消息。相反,假装一切都很酷

对于1)远程连接的超时在PHP的default_socket_timeout设置中定义,默认为60秒。您可以/应该为自己的呼叫设置更低的超时:

$opts = array(
      'http'=>array(
        'timeout'=> 2, // timeout of 2 seconds
        'proxy' => 'tcp://100.100.100.100:80' //a wrong proxy
      )
);

对于2),您通常会使用try/catch块。不幸的是,file_get_contents()是那些不抛出可捕获异常的旧PHP函数之一。

您可以通过在函数调用前加上@符号来抑制可能的错误消息:

$file = @file_get_contents('http://ifconfig.me/ip', false, $context);

但是你根本无法处理任何错误。

如果你想至少有一些错误处理,你应该使用cURL。不幸的是,它也不会抛出异常。但是,如果发生cURL错误,可以使用curl_errno()/curl_error()读取。

以下是用cURL:实现的代码

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://ifconfig.me/ip");
curl_setopt($ch, CURLOPT_PROXY, 'tcp://100.100.100.100:80');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_HEADER, 1);
$data = curl_exec($ch);
$error = curl_errno($ch) ? curl_error($ch) : '';
curl_close($ch);
print_r($error ? $error : $data);

通过这种方式,您可以决定在出现错误时要做什么。