php超时时间说明

一,http请求超时时间

可能出现的场景:php

1,curl进程运行了一个世纪还木结束,curl的时候设置了超时时间 --connect-timeout 1000nginx

2,operation timed out after 1000 milliseconds with 0 bytes receivedapache

3,connect() timed out!浏览器

wget对超时时间, 是有分阶段的, 好比说请求的超时, 传输的超时,一样HTTP请求有两个超时时间:一个是链接超时时间,另外一个是数据传输的最大容许时间,出现问题就要看是哪一个超时时间出问题了。安全

curl命令行

链接超时时间用 --connect-timeout 参数来指定,数据传输的最大容许时间用 -m 参数来指定,时间是毫秒服务器

例如:app

curl --connect-timeout 10 -m 20 "http://***"curl

链接超时的话,出错提示形如:函数

curl: (28) connect() timed out!php-fpm

数据传输的最大容许时间超时的话,出错提示形如:

curl: (28) Operation timed out after 2000 milliseconds with 0 bytes received

使用PHP的curl_init

<?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0);

//链接超时时间 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1000);

//数据传输的最大容许时间 curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // grab URL and pass it to the browser curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch);

//使用curl_error($ch)查看错误的详情 var_dump(curl_error($ch)); 

二,页面执行时间

当你的页面有大量数据时,建议使用set_time_limit()来控制运行时间,配置该页最久执行时间。

设定一个程式所容许执行的秒数,若是到达限制的时间,程式将会传回错误,时间是秒单位。

php.ini:它预设的限制时间是30秒,max_execution_time的值定义在结构档案中,若是将秒数设为0,表示无时间上的限制,修改后从新启动apache/nginx服务器

php代码:set_time_limit(800);

这个函数指定了当前所在php脚本的最大执行时间为800秒,实际上最大执行时间=php.ini里的max_execution_time数值 - 当前脚本已经执行的时间 + 设定值

假如php.ini里的max_execution_time=30,当前脚本已经执行5秒,则:

最大执行时间=30-5+800=825秒。

 

注意 : 当PHP是执行在安全模式时,set_time_limit( )将不会有结果,除非是关闭安全模式或是修改结构档案中的时间限制。

三,php长链接

若是咱们须要一个脚本持续的运行,那么咱们就要经过php长链接的方式,来达到运行目的。经过 set_time_limit 来设置一个脚本的执行时间为无限长;而后使用 flush() 和 ob_flush() 来清除服务器缓冲区,随时输出脚本的返回值。

以下面这段脚本:

<?php
header("Content-Type: text/plain");
set_time_limit(0);
$infoString = "Hello World" . "\n";
while( isset($infoString) )
{
    echo $infoString;
    flush();
    ob_flush();
    sleep(5);
}
?>

当咱们执行后,每隔5秒钟,咱们会获得一行 Hello World ,若是不按中止按钮,浏览器会不停的一行一行继续加载。

经过这一方法,咱们能够完成不少功能,例如机器人爬虫、即时留言板等程序。

若是要中止运行只能重启php-fpm:

查看php-fpm进程数:

ps aux | grep -c php-fpm

查看运行内存

/usr/bin/php  -i|grep mem

重启php-fpm

/etc/init.d/php-fpm restart

相关文章
相关标签/搜索