Summary of several common timeout processing methods in PHP

Source: Internet
Author: User
Tags apache error log
In PHP development, I often use timeout processing to timeout. I will talk about several scenarios, it is convenient for users who need to work in PHP development to use timeout handling to timeout. I will talk about several scenarios:

1. asynchronous data acquisition if a backend data source cannot be obtained successfully, the whole page is not affected.
2. in order to ensure that the Web server will not be unable to access other pages due to poor page processing performance, some page operations will be set
3. in some scenarios where the upload or uncertain processing time is required, you need to set all the timeout values in the entire process to an unlimited value. otherwise, improper configuration of any link will cause inexplicable execution interruption.
4. multiple backend modules (MySQL, Memcached, and HTTP interfaces), in order to prevent poor performance of a single interface, resulting in too slow data acquisition, affecting the page opening speed and causing an avalanche
5 .... Many scenarios that require timeout

Timeout settings need to be considered in all of these places, but timeout in PHP is classified and different processing methods and policies are different. for the system description, I have summarized the commonly used timeout processing in PHP.

Web server timeout processing]

[Apache]
Generally, when the performance is high, all timeout configurations are 30 seconds by default. However, when the file is uploaded or the network speed is very slow, the timeout operation may be triggered.
Currently, apachefastcgiphp-fpm mode has three timeout settings:
Fastcgi timeout settings:
Modify the fastcgi connection configuration of httpd. conf as follows:

The code is as follows:



FastCgiExternalServer/home/forum/apache/apache_php/cgi-bin/php-cgi-socket/home/forum/php5/etc/php-fpm.sock
ScriptAlias/fcgi-bin/"/home/forum/apache/apache_php/cgi-bin /"
AddHandlerphp-fastcgi.php
Actionphp-fastcgi/fcgi-bin/php-cgi
AddTypeapplication/x-httpd-php.php



The default configuration is 30 s. If you need to customize your own configuration, you need to modify the configuration, for example, to 100 s: (restart apache after modification ):

The code is as follows:



FastCgiExternalServer/home/forum/apache/apache_php/cgi-bin/php-cgi-socket/home/forum/php5/etc/php-fpm.sock-idle-timeout100
ScriptAlias/fcgi-bin/"/home/forum/apache/apache_php/cgi-bin /"
AddHandlerphp-fastcgi.php
Actionphp-fastcgi/fcgi-bin/php-cgi
AddTypeapplication/x-httpd-php.php


If the timeout occurs, a 500 error is returned. disconnect from the backend php service and record an apache error log:
[ThuJan2718: 30: 152011] [error] [client10.81.41.110] FastCGI: commwithserver "/home/forum/apache/apache_php/cgi-bin/php-cgi" aborted: idletimeout (30sec)
[ThuJan2718: 30: 152011] [error] [client10.81.41.110] FastCGI: incompleteheaders (0 bytes) receivedfromserver "/home/forum/apache/apache_php/cgi-bin/php-cgi"
Other fastcgi configuration parameters:

The code is as follows:


IdleTimeout
ProcessLifeTime: the maximum life cycle of a process. it is killed unconditionally after expiration.
MaxProcessCount maximum number of processes
DefaultMinClassProcessCount: minimum number of processes started by each program
DefaultMaxClassProcessCount maximum number of processes started by each program
Response timeout of IPCConnectTimeout program
The maximum time for IPCCommTimeout to communicate with the program. The error above may be caused by a small value.
MaxRequestsPerProcess: each process can complete a maximum of processes and commit suicide.


[Lighttpd]
Configuration: lighttpd. conf
In Lighttpd configuration, there are several timeout parameters as follows (write-only timeout is considered in length, and the write timeout parameter is the same ):
Main options:
Server. max-keep-alive-idle = 5
Server. max-read-idle = 60
Server. read-timeout = 0
Server. max-connection-idle =

The code is as follows:


# Maximum number of requests for each keep-alive operation. the default value is 16.
Server. max-keep-alive-requests = 100
# The maximum waiting time of keep-alive, in seconds. the default value is 5.
Server. max-keep-alive-idle = 1200
# Number of work sub-processes in lighttpd. the default value is 0. a single process runs.
Server. max-worker = 2
# Restrict the maximum intermediate pause time (in seconds) during request sending ),
# If the user does not end the request when sending the request, the pause is too long, and the lighttpd will automatically disconnect
# The default value is 60 seconds)
Server. max-read-idle = 1200
# Restrict the maximum intermediate pause time (in seconds) of a user when receiving a response ),
# If the user receives a response (not completed) and the pause takes too long, the lighttpd will automatically disconnect
# The default value is (seconds)
Server. max-write-idle = 12000
# Read client request timeout limit, in seconds. if the value is set to 0, no limit is imposed.
# When the value is smaller than max-read-idle, read-timeout takes effect.
Server. read-timeout = 0
# Timeout limit for writing a response page to the client. the unit is seconds. if the value is set to 0, no limit is imposed.
# Write-timeout takes effect when the value is set to less than max-write-idle
Server. write-timeout = 0
# Maximum request processing time. if mod_proxy_core is used, the interaction time with the backend is limited, in seconds.
Server. max-connection-idle = 1200


Note:
For a continuous request on a keep-alive connection, the maximum interval between sending the first request content is determined by the max-read-idle parameter, starting from the second request, the maximum interval between sending request content is determined by the max-keep-alive-idle parameter. The interval timeout between requests is also determined by max-keep-alive-idle. The total time for sending request content timeout is determined by the read-timeout parameter. The timeout between Lighttpd and backend interaction data is determined by max-connection-idle.
Additional reading:
Http://www.snooda.com/read/244
[Nginx]
Configuration: nginx. conf

The code is as follows:


Http {
# Fastcgi: (for backend fastcgi, fastcgi does not belong to the proxy mode)
Fastcgi_connect_timeout5; # connection timeout
Fastcgi_send_timeout10; # write timeout
Fastcgi_read_timeout10; # read timeout
# Proxy: (effective for proxy/upstreams)
Proxy_connect_timeout15s; # connection timeout
Proxy_read_timeout24s; # read timeout
Proxy_send_timeout10s; # write timeout
}


Note:
Nginx timeout settings are clear and easy to understand. the above timeout settings are applicable to different working modes, but there are many problems caused by timeout.
Additional reading:
Http://hi.baidu.com/pibuchou/blog/item/a1e330dd71fb8a5995ee3753.html
Http://hi.baidu.com/pibuchou/blog/item/7cbccff0a3b77dc60b46e024.html
Http://hi.baidu.com/pibuchou/blog/item/10a549818f7e4c9df703a626.html
Http://www.apoyl.com /? P = 466
[PHP timeout processing]
[PHP-fpm]
Configuration: php-fpm.conf

The code is as follows:




//...
Setsthelimitonthenumberofsimultaneousrequeststhatwillbeserved.
EquivalenttoApacheMaxClientsdirective.
Equivalenttophp_fcgi_childrenvironmentinoriginalphp.fcgi
Usedwithanypm_style.
# Number of php-cgi processes
128
Thetimeout (inseconds) forservingasinglerequestafterwhichtheworkerprocesswillbeterminated
Shouldbeusedwhen 'max _ execution_time 'inioptiondoesnotstopscriptexecutionforsomereason
'0s' means 'off'
# Php-fpm request execution timeout, 0 s is never timeout, otherwise set an Ns as the timeout seconds
0 s
Thetimeout (inseconds) forservingofsinglerequestafterwhichaphpbacktracewillbedumpedtoslow. logfile
'0s' means 'off'
0 s


Note:
In php. ini, max_execution_time can be used to set the maximum execution time of PHP scripts. However, this parameter does not take effect in php-cgi (php-fpm. The maximum execution time of PHP scripts can be controlled:
0 s
That is to say, running max_execution_time in mod_php5.so mode will take effect, but it will not take effect if running in php-fpm mode.
Additional reading:
Http://blog.s135.com/file_get_contents/
[PHP]
Configuration: php. ini
Option:
Max_execution_time = 30
Or set in the code:
Ini_set ("max_execution_time", 30 );
Set_time_limit (30 );
Note:
The setting takes effect for the current session. for example, if the setting 0 never times out, but if the php safe_mode is enabled, these settings will not take effect.
The results are the same, but you need to refer to the php-fpm content. if request_terminate_timeout is set in php-fpm, max_execution_time will not take effect.
[Backend & interface access timeout]
[HTTP access]
Generally, there are many HTTP access methods, such as curl, socket, and file_get_contents.
If the other server never responds, we will suffer. it is easy to get rid of the entire server. Therefore, timeout needs to be considered when accessing http.
[CURL access HTTP]
CURL is a commonly used lib library for accessing HTTP protocol interfaces with high performance and some features supported by concurrency.
CURL:
Curl_setopt ($ ch, opt) can be used to set timeout settings, including:
* (Important) CURLOPT_TIMEOUT sets the maximum number of seconds that cURL can be executed.
* (Important) CURLOPT_TIMEOUT_MS sets the maximum number of milliseconds that cURL can be executed. (Added in cURL7.16.2. It can be used from PHP5.2.3 .)
CURLOPT_CONNECTTIMEOUT is the waiting time before the connection is initiated. if it is set to 0, it will wait infinitely.
CURLOPT_CONNECTTIMEOUT_MS indicates the waiting time for the connection attempt, in milliseconds. If it is set to 0, the system waits for no limit. Added to cURL7.16.2. Available from PHP5.2.3.
CURLOPT_DNS_CACHE_TIMEOUT sets the time for saving DNS information in the memory. the default value is 120 seconds.
Curl common second-level timeout:
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_TIMEOUT, 60); // you only need to set the number of seconds.
Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ headers );
Curl_setopt ($ ch, CURLOPT_USERAGENT, $ defined_vars ['http _ USER_AGENT ']);
Curl common timeout in seconds:
Curl_setopt ($ ch, CURLOPT_TIMEOUT, 60 );
Curl needs to be added if millisecond timeout is required:
Curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1L );
Or:
Curl_setopt ($ ch, CURLOPT_NOSIGNAL, true); supports millisecond-level timeout settings
Example of curl timeout in milliseconds:

The code is as follows:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.