In the actual development of PHP many times we will use file_get_contents this function to get the contents of the remote page return, but if the remote response time is very slow, file_get_contents () will be stuck there, will not time out, At this time we will sometimes find the Web services of the Linux server, the sudden increase in system load, using the top command to view, many php-cgi process CPU utilization is close to 100%.
We know that in php.ini, there is a parameter max_execution_time can set the maximum execution time for PHP scripts, but in php-cgi (PHP-FPM), this parameter will not work. The real ability to control the maximum execution time for PHP scripts is the following parameters in the php-fpm.conf configuration file:
C code
The timeout (in seconds) for serving a single request after which the worker process'll be terminated
Should be used when ' max_execution_time ' ini option does not stop script execution for some reason
' 0s ' means ' off '
<value name= "Request_terminate_timeout" >0s</value>
The default value is 0 seconds, which means that the PHP script will continue to execute. This way, when all the php-cgi processes are stuck in the file_get_contents () function, this WebServer can no longer process the new PHP request to modify the parameter, setting a PHP script maximum execution time is necessary, but the symptom is not a cure. For example, change to <value name= "Request_terminate_timeout" >30S</VALUE> if file_get_contents () gets a slower page content, this means that 150 A php-cgi process that can handle only 5 requests per second, WebServer is also hard to avoid "502 bad Gateway".
To do a thorough solution, only PHP programmers can get rid of the habit of directly using file_get_contents ("http://example.com/"), but slightly modified, add a time-out, in the following way to implement an HTTP GET request. If you feel trouble, you can encapsulate the following code as a function yourself.
<?php $ctx = stream_context_create (Array (' http ' = = = Array ( ' timeout ' = 1//Set a time-out, in seconds ) ) ); File_get_contents ("http://example.com/", 0, $ctx); ? >