我使用下面的函数获取在云中托管的图像文件的大小。我需要我的网页上显示该尺寸。当页面第一次加载它返回一个通知:未定义指数:内容长度。当重新加载页面,通知消失,并显示在页面的罚款。这究竟是为什么,我应该怎么办呢?
$post_id = get_the_ID();
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
//retrieve the size in bytes
$filePath = get_the_post_thumbnail_url($post_id, 'full');
if (filter_var($filePath, FILTER_VALIDATE_URL)) {
$ch = curl_init();
$headers = [];
curl_setopt($ch, CURLOPT_URL, $filePath);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// this function is called by curl for each header received
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$name = strtolower(trim($header[0]));
if (!array_key_exists($name, $headers))
$headers[$name] = [trim($header[1])];
else
$headers[$name][] = trim($header[1]);
return $len;
}
);
$data = curl_exec($ch);
}
//convert the size in bytes to MB
$filemb = $headers['content-length']['0'] / 1000 / 1000;
$filemb = round($filemb,2);
// do my stuff
除其他事情,我把04FS和杰弗里的建议,制定了不同的方法。我在WooCommerce创建的自定义字段(文件大小),并且在产品的创建,我设置字段与由上述函数返回的值。
所以,我将它存储在我自己的数据库。正因为如此,该页面的速度也不会下降。我想这也将是对带宽的使用是有益的。
因此,它只能检索一次。
@ 04FS和@Geoffrey ....谢谢!
编辑:
看来终究不可靠。有时它被设定,有时不>不得不搞懂这个问题.....