What are the methods to set PHP timeout?
This article will introduce you to how to set PHP timeout. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
1. PHP file execution timeout
(1) Initial setting script execution time
Open the php.ini file and find:
max_execution_time=30
Modify to:
max_execution_time=600
If you do not have server modification permissions, you can set the timeout through the built-in PHP script method and add the following code to the PHP file that needs to perform long-term operations:
<?php ini_set('max_execution_time', 600);//秒为单位,自己根据需要定义
You can also set the timeout through the .htaccess file and add the following code in the file:
php_value max_execution_time 600
(2) Reset the script execution time and reset the timer
set_time_limit (int $seconds): bool
seconds------Maximum execution time, unit is seconds. If set to 0 (zero), there is no time limit.
Set the time allowed for the script to run, in seconds. If this setting is exceeded, the script returns a fatal error. The default value is 30 seconds, or the value defined in max_execution_time in php.ini, if this value exists.
When this function is called, set_time_limit() will restart the timeout counter from zero. In other words, if the default timeout is 30 seconds and set_time_limit(20) is called when the script has been running for 25 seconds, then the total time the script can run before timing out is 45 seconds.
2. PHP Curl request timeout
Curl is a commonly used lib library for accessing the HTTP protocol interface. It has high performance and some concurrent support functions.
curl_setopt($ch, opt) You can set some timeout settings, mainly including:
a, CURLOPT_TIMEOUT sets the maximum number of seconds that CURL is allowed to execute.
b. CURLOPT_TIMEOUT_MS sets the maximum number of milliseconds that CURL is allowed to execute.
c. CURLOPT_CONNECTTIMEOUT The time to wait before initiating a connection. If set to 0, it will wait indefinitely.
d. CURLOPT_CONNECTTIMEOUT_MS The time to wait for a connection attempt, in milliseconds. If set to 0, wait infinitely.
e. CURLOPT_DNS_CACHE_TIMEOUT sets the time to save DNS information in memory, the default is 120 seconds.
3. PHP Socket request timeout
<?php $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO,array("sec"=> 1, "usec"=> 0 ) ); // 接收 socket_set_option($socket,SOL_SOCKET,SO_SNDTIMEO,array("sec"=> 3, "usec"=> 0 ) ); // 发送
Although PHP has a timeout parameter for connecting to the socket for the fsockopen() method, there is no timeout parameter for reading and writing data after a successful connection in C. set up. It doesn't matter, PHP provides a series of methods for streams to prevent timeouts.
stream_set_blocking( $fp , false )
Set the data flow to blocking mode to prevent exiting before the data is read.
If the mode is false, the given socket descriptor will switch to non-block mode. If it is true, Then switch to block mode. This effect is similar to fgets() reading from socket. In non-block mode, fgets() will return immediately, while in block mode, it will wait for the data to meet the requirements.
stream_set_timeout( $fp , 10 )
Set the timeout. This sentence should be added immediately after the connection is successfully established. The following parameter unit is seconds.
Obtain the header/metadata from the encapsulation protocol file pointer and return a Array, the format of which is:
Array ( [stream_type] => tcp_socket [mode] => r+ [unread_bytes] => 0 [seekable] => [timed_out] => [blocked] => 1 [eof] => )
The index timed_out is the timeout information, if it times out, it is true, if it has not timed out, it is false. We can use this to judge whether the socket has timed out. It should be noted that this sentence should be added After each statement that needs to be waited for, such as fwrite(), fread(), and every time it is read, it must be judged whether it times out, and for a connection, only one timeout setting stream_set_timeout ( $fp , 10 ) is enough.
$fp = @fsockopen( $ip , $port, $errNo , $errstr, 30 ); if( !$fp ) { return false; } else { stream_set_timeout( $fp , 3 ) ; //发送数据 fwrite( $fp , $packet ) ; $status = stream_get_meta_data( $fp ) ; //发送数据超时 if( $status['timed_out'] ) { echo "Write time out" ; fclose( $fp ); return false; } //读取数据 $buf = fread( $fp , 16 ) ; $status = stream_get_meta_data( $fp ) ; //读取数据超时 if( $status['timed_out'] ) { echo "Read time out" ; fclose( $fp ); return false; } }
4. File_get_contents timeout processing (encapsulating socket, file_put_contents is similar)
Starting from PHP5, file_get_content already supports context (the manual says: 5.0.0 Added the context support.), In other words, starting from 5.0, file_get_contents can actually POST data. Similar ones include fopen (context support has also been added since PHP5) and file (support has been added in PHP5).
<?php $get_opts = array( 'http'=>array( 'method' => "GET", 'timeout' => 1,//单位秒, 默认使用php.ini中default_socket_timeout的设置 ) ); $post_opts = array( 'http'=>array( 'method' => "POST", 'timeout' => 60,//单位秒, 可用ini_set('default_socket_timeout', 120);进行默认设置 'content' => http_build_query($param_array, '', '&') ) ); $opts = $get_opts; $res = file_get_contents($url, FALSE, stream_context_create($opts)); //返回string,失败返回FALSE
5. PHP Soap request timeout
ini_set('default_socket_timeout', 30); //定义响应超时为30秒 try { $options = array( 'cache_wsdl' => 0, 'connection_timeout' => 5, //定义连接超时为5秒,默认php.ini中default_socket_timeout的值 ); libxml_disable_entity_loader(false); $client = new \SoapClient($url, $options); return $client->__soapCall($function_name, $arguments); } catch (\SoapFault $e) { //超时、连接不上 if($e->faultcode == 'HTTP'){ throw new TimeoutException('连接或请求超时', $e->getCode()); } }
soap request can also use the resource stream context, and the request timeout can be written to stream_context_create().
try { $arrContextOptions=array("ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false,'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT)); //$arrContextOptions=array("http"=>array( "method"=>'GET', 'timeout'=>10)); $options = array( 'soap_version'=>SOAP_1_2, 'exceptions'=>true, 'trace'=>1, 'cache_wsdl'=>WSDL_CACHE_NONE, 'stream_context' => stream_context_create($arrContextOptions) ); $client = new SoapClient('https://url/dir/file.wsdl', $options); } catch (Exception $e) { echo "<h2>Exception Error!</h2>"; echo $e->getMessage(); }
Recommended learning: php video tutorial
The above is the detailed content of What are the methods to set PHP timeout?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total
