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

Solução para o problema de tempo de espera da solicitação de endereço remoto no PHP

Configuração de tempo de espera de solicitação de endereço remoto da solicitação php, explicando principalmente os métodos de configuração de tempo de espera dos três funções simples e comuns file_get_contents, fopen, curl. Geralmente, é recomendado usar curl, que é o melhor em desempenho e eficiência.

1Configuração de tempo de espera de solicitação file_get_contents

$timeout = array(
'http' => array(
'timeout' =>5//Definir um tempo de espera, unidade em segundos
)
);
$ctx = stream_context_create($timeout);
$text = file_get_contents("https://pt.oldtoolbag.com/",0, $ctx);

2Configuração de tempo de espera de solicitação fopen

$timeout = array(
'http' => array(
'timeout' => 5 //Definir um tempo de espera, unidade em segundos
)
);
$ctx = stream_context_create($timeout);
if ($fp = fopen("https://pt.oldtoolbag.com/", "r", false, $ctx)) {
while( $c = fread($fp, 8192)) {
echo $c;
}
fclose($fp);
}

3,curl timeout request setting

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

curl_setopt($ch, opt) 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 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_URL,$url);
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 the PHP request remote address brought to you by the editor. I hope everyone will support and cheer for the tutorial~

Você também pode gostar