php - PHP中处理脚本超时

标签 php

我被要求编写一个脚本,该脚本将解析页面中的所有 href,然后访问每个 href 并检查每个页面是否已启动并正在运行(使用来自 CURL 调用的 HTTP 代码)。我有如下内容:

<?php foreach($links_array as $link_array): //$links_array are a tags
                $link_array=str_replace("'", "\"", $link_array); // if href='link' instead of href="link"
                $href= get_attribute($link_array, "href");
                $resolved_address= resolve_address($href, $page_base);
                $download_href= http_get($resolved_address,$ref );
                $url=$download_href['STATUS']['url'];
                $http_code=$download_href['STATUS']['http_code'];
                $total_time=$download_href['STATUS']['total_time'];
                $message=$status_code_array[$download_href['STATUS']['http_code']];
                // $status_code_array is an array 
                //if you refer to its index using the http code it give back the human
                //readable message of the code 
                ?>
                <tr>
                <td><?php echo $url ?></td>
                <td><?php echo $http_code ?></td>
                <td><?php echo $http_code ?></td>
                <td><?php echo $total_time ?></td>
                </tr>
           <?php endforeach;?>

该脚本适用于具有少量 href 的页面,但如果页面具有大量 href,则脚本会超时。我尝试增加 php.ini 中的 max_execution_time 但这似乎不是一个优雅的解决方案。我的问题是 1) 在这些需要很长时间执行的情况下,生产软件如何工作。 2) 我可以通过捕获致命的“超过 60 秒的最大执行时间”错误来继续进行 CURL 调用吗? 3)如果我可以对第一个 href 进行curl 调用,检查代码,使用 HTML 打印它,然后对第二个 href 进行下一个curl 调用,检查代码,打印它等等,那就更好了。我怎样才能做到这一点 ?

请坦白我的无知,我已经进入网络编程三个月了。

最佳答案

您可以在 php.ini 文件中设置 max_execution_time。确保您使用的是正确的文件,因为可能有两个文件(一个用于 fpm,一个用于 cli)。

您可以在此处查看您的文件:

php --ini

您还可以在脚本中设置执行时间。

ini_set('max_execution_time', 300);

或者,您也可以在 php 命令中设置时间。

php -dmax_execution_time=300 script.php

回答您的其他问题:

How does production software works in these type of cases

一种方法(在 PHP 中)是使用worker (RabbitMQ/AMQP)。这意味着您有一个脚本将消息“发送”到队列和 n 个工作线程中。这些工作人员从该队列中提取消息,直到队列为空。

https://github.com/php-amqplib/php-amqplib

Can I continue making CURL calls by catching the fatal "Maximum execution time of 60 seconds exceeded"error

是的,但是没有抛出异常。您可以通过以下方式实现它:

if (curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}

关于php - PHP中处理脚本超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52578309/

相关文章:

php - 是否可以在 javascript 中使用 PHP 定义的变量?

php - 计算一个月的剩余天数

PHP(Nette框架)自动编码标准检查

php - 动态类别的数据库架构

php - Laravel 通过中间件授权

php - 可以在mysql数据末尾加一个值吗?

php - 对 PHP 标签进行编码以确保安全?

php - 联系表单 7 提交后无法执行脚本

php - 是否可以指望 header() 重定向来结束程序流程?

php - 阻止 ip 从 iptables 到 mysql