php - get_headers 在外部服务器无响应时添加跳过
问题描述
我使用以下代码检查外部 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 获取标头
推荐阅读
- javascript - 重复功能实现
- python - Python在运行OpenCV时随机退出而不抛出异常
- c - 如何在ac程序中启用或禁用关键字的字符
- angular - 如何为 mat-paginator 设置条件语句?
- javascript - 是否可以使用 JQuery 或 JavaScript 给类和标题小写字母?
- python - 使用 tensorflow serving 和 docker 服务通用句子编码器模型
- r - R-marrangeGrob 独特的传奇
- amazon-web-services - 从本地 Jenkins 部署云形成
- sql - 查找表中某个值出现的时间段
- java - IntelliJ 右键单击时没有运行按钮