【问题标题】:get_headers add skip when external server not responding [duplicate]get_headers 在外部服务器没有响应时添加跳过[重复]
【发布时间】:2019-05-27 04:36:12
【问题描述】:

我使用以下代码检查外部 pdf 的文件大小。 但是如果外部服务器在 1 秒内没有响应,我想添加一个超时并跳过。我怎样才能做到这一点?

我当前的代码:

<?php
$newmanual = "https://www.example.com/file.pdf"
$head = array_change_key_case(get_headers($newmanual, TRUE)); 
$filesize = $head['content-length'];?>

【问题讨论】:

    标签: php get-headers


    【解决方案1】:

    Curl 有一个超时功能,你可以用它来获取标题。

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://www.example.com/file.pdf");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    //get only headers
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    // The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); 
    // The maximum number of seconds to allow cURL functions to execute.
    curl_setopt($ch, CURLOPT_TIMEOUT, 20); //timeout in seconds
    
    $output = curl_exec($ch);
    // close handle
    curl_close($ch);
    
    $headers = [];
    $data = explode("\n",$output);
    $headers['status'] = $data[0];
    array_shift($data);
    
    foreach($data as $part){
        $middle=explode(":",$part);
        $headers[trim($middle[0])] = trim($middle[1]);
    }
    
    echo "<pre>";
    var_dumo(headers);
    

    代码取自帖子how to set curl timeoutget header from php curl

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 2012-09-23
      • 2016-07-20
      • 1970-01-01
      相关资源
      最近更新 更多