Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.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 当使用错误的代理服务器时,如何处理500个内部服务器错误?_Php_Error Handling_Proxy_File Get Contents - Fatal编程技术网

Php 当使用错误的代理服务器时,如何处理500个内部服务器错误?

Php 当使用错误的代理服务器时,如何处理500个内部服务器错误?,php,error-handling,proxy,file-get-contents,Php,Error Handling,Proxy,File Get Contents,如果我在PHP中使用错误的代理运行此代码,我会得到500个内部服务器错误。 如何处理并继续执行 $opts = array( 'http'=>array( 'method'=>"GET", 'proxy' => 'tcp://100.100.100.100:80' //a wrong proxy ) ); $context = stream_context_create($opts);

如果我在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);

我想你说“处理”的意思是两件事:

  • 如果脚本连接到“错误”的代理,它将等待很长时间建立连接,直到超时。脚本应该设置一个较低的超时,这样用户就不会永远等待
  • 如果在访问外部ressource期间发生错误,请不要死掉或显示难看的消息。相反,假装一切都很酷
  • 对于1)远程连接的超时在PHP的
    default\u socket\u 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\u get\u contents()
    是那些不抛出可捕获异常的旧PHP函数之一

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

    $file = @file_get_contents('http://ifconfig.me/ip', false, $context);
    
    但是你根本无法处理任何错误

    如果您希望至少有一些错误处理,那么应该使用。不幸的是,它也不会抛出异常。但是,如果发生卷曲错误,可以使用
    cURL\u errno()
    /
    cURL\u 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);
    

    通过这种方式,您可以决定在出现错误时要执行的操作。

    您所说的“处理”是什么意思?运行此代码的机器发出500,或者您尝试点击的代理/url发出500?运行此代码的机器发出500。我不希望它停止下一个代码。@jay blanchard我的意思是它必须忽略由文件内容引起的500个错误,并继续执行最终的下一个代码。这种cURL方法将显示cURL错误,如error
    58
    CURLE\u SSL\u CERTPROBLEM
    。它不会处理HTTP 500错误。对于这些问题,请查看以下答案:。此外,出于某种原因,此代码使用
    CURLOPT_HEADER
    将HTTP头粘贴到数据上。这不是很方便。根据cURL手册,“如果不详细了解正在使用的协议,就不可能再次准确地将它们分开。”