使用php获取另一个域上的js文件的文件大小


Get the filesize of a js file on another domain using php

如何在另一个网站上获得js文件的文件大小。我正在尝试创建一个监视器来检查js文件是否存在,以及它是否超过了0字节。

例如,在bar.com上,我会有以下代码:

$filename = 'http://www.foo.com/foo.js';
echo $filename . ': ' . filesize($filename) . ' bytes';

您可以使用HTTP HEAD请求。

<?php
 $url = "http://www.neti.ee/img/neti-logo.gif";
 $head = get_headers($url, 1);
 echo $head['Content-Length'];
?>

注意:这不是一个真正的HEAD请求,而是PHP解析其Content-Length的GET请求。不幸的是,PHP函数的名称有很大的误导性。对于较小的js文件来说,这可能已经足够了,但对于较大的文件大小,请使用带有Curl的真实HTTP Head请求,因为这样服务器就不必上传整个文件,只需发送标头。

对于这种情况,请使用Jakub提供的代码。

只需使用CURL,这里列出了一个非常好的例子:
参考:http://www.php.net/manual/en/function.filesize.php#92462

<?php
$remoteFile = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
  echo 'cURL failed';
  exit;
}
$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP'/1'.[01] ('d'd'd)/', $data, $matches)) {
  $status = (int)$matches[1];
}
if (preg_match('/Content-Length: ('d+)/', $data, $matches)) {
  $contentLength = (int)$matches[1];
}
echo 'HTTP Status: ' . $status . "'n";
echo 'Content-Length: ' . $contentLength;
?>

结果:

HTTP状态:302
内容长度:8808759

另一个解决方案。http://www.php.net/manual/en/function.filesize.php#90913

这只是一个两步过程:

  1. 抓取js文件并将其存储到变量中
  2. 检查js文件的长度是否大于0

就是这样!!

以下是如何在PHP 中完成

<?php
$data = file_get_contents('http://www.foo.com/foo.js');
if(strlen($data)>0):
    echo "yay"
else:
    echo "nay"
?>

注意:你可以按照Uku的建议使用HTTP Head,但如果你正在寻找页面内容,如果js文件有内容,那么你就必须再次爬网:(