温馨提示×

如何设置PHP put请求的超时

PHP
小樊
87
2024-07-31 13:36:10
栏目: 编程语言

在 PHP 中,可以通过设置 CURLOPT_TIMEOUTCURLOPT_CONNECTTIMEOUT 选项来设置 PUT 请求的超时时间。以下是一个示例代码:

$ch = curl_init();
$url = 'http://example.com/api/resource';
$data = array('name' => 'John', 'age' => 30);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置请求超时时间为 30 秒
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 设置连接超时时间为 10 秒

$response = curl_exec($ch);
if ($response === false) {
    echo 'Error: ' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);

在上面的示例中,CURLOPT_TIMEOUT 选项设置了请求超时时间为 30 秒,CURLOPT_CONNECTTIMEOUT 选项设置了连接超时时间为 10 秒。当请求超时或连接超时时,curl_exec() 函数会返回 false,可以通过 curl_error() 函数获取错误信息。

0