在 PHP 中,使用 file_get_contents($url) 函数进行网络请求时,默认情况下没有超时设置。如果请求的远程 URL 响应时间过长,可能会导致脚本挂起。为了解决这个问题,可以使用 stream_context_create 函数来设置超时参数。
以下是如何设置超时的具体步骤和示例代码。
1. 设置超时的基本方法
使用 stream_context_create 创建一个流上下文,并设置 http 选项中的 timeout 参数。
示例代码
<?php $url = "http://www.example.com";
$options = [ "http" => [ "timeout" => 5 ] ];
$context = stream_context_create($options);
$response = @file_get_contents($url, false, $context);
if ($response === FALSE) { echo "请求失败或超时。\n"; } else { echo "请求成功:\n"; echo $response; } ?>
|
2. 代码说明
stream_context_create($options):创建一个流上下文,$options 数组中设置 HTTP 请求的选项。
"timeout" => 5:设置超时时间为 5 秒。可以根据需要调整这个值。
@ 符号:用于抑制警告,防止在请求失败时输出错误信息。
3. 处理错误
在实际应用中,建议对请求失败或超时的情况进行处理。可以根据具体需求添加更多的错误处理逻辑。例如:
if ($response === FALSE) { $error = error_get_last(); echo "请求失败,错误信息: " . $error['message'] . "\n"; }
|
4. 其他选项
除了设置超时,还可以添加其他 HTTP 选项,例如:
method:设置请求方法(如 GET, POST)。
header:设置请求头。
content:设置 POST 请求的内容。
示例:POST 请求
<?php $url = "http://www.example.com/api"; $data = http_build_query(['param1' => 'value1', 'param2' => 'value2']);
$options = [ "http" => [ "header" => "Content-type: application/x-www-form-urlencoded\r\n", "method" => "POST", "content" => $data, "timeout" => 5 ] ];
$context = stream_context_create($options); $response = @file_get_contents($url, false, $context);
if ($response === FALSE) { $error = error_get_last(); echo "请求失败,错误信息: " . $error['message'] . "\n"; } else { echo "请求成功:\n"; echo $response; } ?>
|