English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Solution to Set Timeout Time for Remote Address Requests in PHP

This article mainly explains how to set timeout time for remote address requests using php, mainly focusing on the timeout settings of the three commonly used functions file_get_contents, fopen, and curl. Generally, it is recommended to use curl as it has the best performance and efficiency.

1Timeout setting for file_get_contents request

$timeout = array(
'http' => array(
'timeout' =>5//Set a timeout time, unit in seconds
)

$ctx = stream_context_create($timeout);
$text = file_get_contents("https://www.oldtoolbag.com/", 0, $ctx);

2Timeout setting for fopen request

$timeout = array(
'http' => array(
'timeout' => 5 //Set a timeout time, unit in seconds
)

$ctx = stream_context_create($timeout);
if ($fp = fopen("https://www.oldtoolbag.com/", "r", false, $ctx)) {
while( $c = fread($fp, 8192)) {
echo $c;
}
fclose($fp);
}

3, curl request timeout settings

CURL is a commonly used lib library for accessing HTTP protocol interfaces, with high performance and some concurrent support features.

curl_setopt($ch, opt) can set some timeout settings, mainly including:

a、CURLOPT_TIMEOUT sets the longest seconds allowed for cURL to execute.

b、CURLOPT_TIMEOUT_MS sets the longest milliseconds allowed for cURL to execute.

c、CURLOPT_CONNECTTIMEOUT is the time to wait before initiating the connection. If set to 0, it will wait indefinitely.

d、CURLOPT_CONNECTTIMEOUT_MS is the time to wait for the connection attempt, in milliseconds. If set to 0, it will wait indefinitely. e、CURLOPT_DNS_CACHE_TIMEOUT sets the time to keep DNS information in memory, the default is120 seconds.

$ch = curl_init();

curl_setopt($ch, CURLOPT_RETURNTRANSFER,1
curl_setopt($ch, CURLOPT_TIMEOUT,60);  //You only need to set a number of seconds.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);

This is the full content of the solution to set the timeout time for PHP to request a remote address that I have brought to you. I hope everyone will support and cheer for the tutorial~

You May Also Like