我使用以下代码检查外部 pdf 的文件大小。但是如果外部服务器在 1 秒内没有响应,我想添加一个超时并跳过。我怎样才能做到这一点?
我当前的代码:
<?php
$newmanual = "https://www.example.com/file.pdf"
$head = array_change_key_case(get_headers($newmanual, TRUE));
$filesize = $head['content-length'];?>
我使用以下代码检查外部 pdf 的文件大小。但是如果外部服务器在 1 秒内没有响应,我想添加一个超时并跳过。我怎样才能做到这一点?
我当前的代码:
<?php
$newmanual = "https://www.example.com/file.pdf"
$head = array_change_key_case(get_headers($newmanual, TRUE));
$filesize = $head['content-length'];?>
Curl 有一个超时功能,您可以使用它来获取标题。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/file.pdf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
//get only headers
curl_setopt($ch, CURLOPT_NOBODY, 1);
// The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
// The maximum number of seconds to allow cURL functions to execute.
curl_setopt($ch, CURLOPT_TIMEOUT, 20); //timeout in seconds
$output = curl_exec($ch);
// close handle
curl_close($ch);
$headers = [];
$data = explode("\n",$output);
$headers['status'] = $data[0];
array_shift($data);
foreach($data as $part){
$middle=explode(":",$part);
$headers[trim($middle[0])] = trim($middle[1]);
}
echo "<pre>";
var_dumo(headers);
从帖子中获取的代码如何设置 curl 超时 并从 php curl 获取标头