curl Setting Timeout Instance of php
- 2021-07-24 10:24:20
- OfStack
In this paper, the timeout setting method of curl in php is described as an example. Share it for your reference. The specific implementation method is as follows:
There are many ways to access HTTP, such as curl, socket, file_get_contents (), etc.
When accessing http, you need to consider the problem of timeout.
CURL Access HTTP:
CURL is a commonly used lib library for accessing HTTP protocol interface, with high performance and some concurrent support functions.
curl_setopt ($ch, opt) can set some timeout settings, mainly including:
① (Important) CURLOPT_TIMEOUT Sets the maximum number of seconds cURL is allowed to execute.
② (Important) CURLOPT_TIMEOUT_MS Sets the maximum number of milliseconds that cURL is allowed to execute.
(Added in cURL 7.16. 2. Available from PHP 5.2. 3)
③ The waiting time of CURLOPT_CONNECTTIMEOUT before initiating the connection. If it is set to 0, it will wait indefinitely.
CURLOPT_CONNECTTIMEOUT_MS wait time, in milliseconds, for connection attempts. If set to 0, it waits indefinitely. (Added in cURL 7.16. 2. Available from PHP 5.2. 3)
⑤ CURLOPT_DNS_CACHE_TIMEOUT sets the time to save DNS information in memory, and the default is 120 seconds.
1. curl normal second 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 1 The number of seconds will be fine
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
2. curl normal second timeout use:
curl_setopt($ch, CURLOPT_TIMEOUT,60);
3. If the millisecond timeout is required for curl, it needs to be added:
curl_easy_setopt(curl, CURLOPT_NOSIGNAL,1L);
// Or
curl_setopt ( $ch, CURLOPT_NOSIGNAL,true);// Support millisecond timeout setting
I hope this article is helpful to everyone's PHP programming.