douyi4544 2017-12-19 15:25
浏览 142
已采纳

php - 如果需要很长时间执行[重复],跳转到foreach的下一个成员

This question already has an answer here:

I have this code for checking urls:

function check_url($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    $headers = curl_getinfo($ch);
    curl_close($ch);
    return $headers['http_code'];
}

And my arrays:

$urls = array(1,2,3,"AAAA",4,5,6,7,8,9);

(For example AAAA takes 200ms and others takes 4s)

And this is my loop

foreach ($urls as $url) {
    check_url("http://www.example.com/" . $url);
}

Question is how can I set a timeout for each member? I mean, If checking member takes more than 2ms, jump to next member.

</div>
  • 写回答

1条回答 默认 最新

  • doutong4088 2017-12-19 16:01
    关注

    If you are using PHP version newer, than 5.2.3, you can use CURLOPT_TIMEOUT_MS curl option to do that.

    So, in essence:

    <?php
    function check_url($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
        $data = curl_exec($ch);
        $headers = curl_getinfo($ch);
        curl_close($ch);
        return empty($headers['http_code']) ? 0 : $headers['http_code'];
    }
    
    $urls = array('http://www.google.com', 'http://www.tatawilkolak.pl');
    
    foreach ($urls as $url) {
        echo check_url($url) . " ";
    }
    ?>
    

    If URL timeout'ed, returned HTTP code will be 0. In my code I have set 200ms as a timeout, but you can play with this number.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改