Table of Contents
1. PHP file execution timeout
(1) Initial setting script execution time
2. PHP Curl request timeout
3. PHP Socket request timeout
4. File_get_contents timeout processing (encapsulating socket, file_put_contents is similar)
5. PHP Soap request timeout
Home Backend Development PHP Problem What are the methods to set PHP timeout?

What are the methods to set PHP timeout?

May 26, 2021 pm 05:23 PM
php time out

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.

What are the methods to set PHP timeout?

1. PHP file execution timeout

(1) Initial setting script execution time

Open the php.ini file and find:

max_execution_time=30
Copy after login

Modify to:

max_execution_time=600
Copy after login

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(&#39;max_execution_time&#39;, 600);//秒为单位,自己根据需要定义
Copy after login

You can also set the timeout through the .htaccess file and add the following code in the file:

php_value max_execution_time 600
Copy after login

(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 ) );  // 发送
Copy after login

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 )
Copy after login

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 )
Copy after login

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] =>
)
Copy after login

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[&#39;timed_out&#39;] )
  {
    echo "Write time out" ;
    fclose( $fp );
    return false;
  }
  //读取数据
  $buf = fread( $fp , 16 ) ;
  $status = stream_get_meta_data( $fp ) ;
  //读取数据超时
  if( $status[&#39;timed_out&#39;] )
  {
    echo "Read time out" ;
    fclose( $fp );
    return false;
  }
}
Copy after login

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(   
  &#39;http&#39;=>array(   
    &#39;method&#39; => "GET",   
    &#39;timeout&#39; => 1,//单位秒, 默认使用php.ini中default_socket_timeout的设置
   )   
);
$post_opts = array(
&#39;http&#39;=>array(   
    &#39;method&#39; => "POST",   
    &#39;timeout&#39; => 60,//单位秒, 可用ini_set(&#39;default_socket_timeout&#39;, 120);进行默认设置
    &#39;content&#39; =>  http_build_query($param_array, &#39;&#39;, &#39;&&#39;)
   )   
);
 
$opts = $get_opts;
$res = file_get_contents($url, FALSE, stream_context_create($opts)); //返回string,失败返回FALSE
Copy after login

5. PHP Soap request timeout

    ini_set(&#39;default_socket_timeout&#39;, 30); //定义响应超时为30秒
 
    try {
      $options = array(
        &#39;cache_wsdl&#39; => 0,
        &#39;connection_timeout&#39; => 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 == &#39;HTTP&#39;){
        throw new TimeoutException(&#39;连接或请求超时&#39;, $e->getCode());
      }
    }
Copy after login

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,&#39;crypto_method&#39; => STREAM_CRYPTO_METHOD_TLS_CLIENT));
 
          //$arrContextOptions=array("http"=>array( "method"=>&#39;GET&#39;, &#39;timeout&#39;=>10));
         $options = array(
                 &#39;soap_version&#39;=>SOAP_1_2,
                 &#39;exceptions&#39;=>true,
                 &#39;trace&#39;=>1,
                 &#39;cache_wsdl&#39;=>WSDL_CACHE_NONE,
                 &#39;stream_context&#39; => stream_context_create($arrContextOptions)
         );
         $client = new SoapClient(&#39;https://url/dir/file.wsdl&#39;, $options);
     
     } catch (Exception $e) {
         echo "<h2>Exception Error!</h2>";
         echo $e->getMessage();
     }
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles