PHP:使用strlen获取远程文件大小? (html)
我正在查看 fsockopen 之类的 PHP 文档,他们说你不能在远程文件上使用 filesize() 而不用 ftell 或其他东西做一些疯狂的事情(不确定他们到底说了什么),但我有一个很好的想法怎么做:
$file = file_get_contents("http://www.google.com");
$filesize = mb_strlen($file) / 1000; //KBs, mb_* in case file contains unicode
这是一个好方法吗?当时看起来很简单,很好用,只是想知道这是否会遇到问题或者不是真实的文件大小。
我只想在文本(网站)上使用它,而不是二进制。
I was looking at PHP docs for fsockopen and whatnot and they say you can't use filesize() on a remote file without doing some crazy things with ftell or something (not sure what they said exactly), but I had a good thought about how to do it:
$file = file_get_contents("http://www.google.com");
$filesize = mb_strlen($file) / 1000; //KBs, mb_* in case file contains unicode
Would this be a good method? It seemed so simple and good to use at the time, just want to get any thoughts if this could run into problems or not be the true file size.
I only wish to use this on text (websites) by the way not binary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个答案需要 PHP5 和 cUrl。它首先检查标头。如果未指定 Content-Length,它将使用 cUrl 下载它并检查大小(但文件不会保存在任何地方 - 只是暂时保存在内存中)。
This answer requires PHP5 and cUrl. It first checks the headers. If Content-Length isn't specified, it uses cUrl to download it and check the size (the file is not saved anywhere though--just temporarily in memory).
您应该查看 get_headers() 函数。它将从 HTTP 请求返回 HTTP 标头的哈希值。
Content-length
标头可能可以更好地判断实际内容的大小(如果存在)。话虽如此,您确实应该使用 curl 或 < a href="https://www.php.net/manual/en/context.http.php" rel="nofollow noreferrer">streams 执行 HEAD 请求而不是 GET。
Content-length
应该存在,这样可以节省传输时间。它将更快、更准确。You should look at the get_headers() function. It will return a hash of HTTP headers from an HTTP request. The
Content-length
header may be a better judge of the size of the actual content, if it's present.That being said, you really should use either curl or streams to do a HEAD request instead of a GET.
Content-length
should be present, which saves you the transfer. It will be both faster and more accurate.它将获取整个文件,然后根据检索到的数据计算文件大小(而不是字符串长度)。通常,filesize 可以直接从文件系统得知文件大小,而无需先读取整个文件。
所以这会相当慢,并且每次都会在能够检索文件大小(字符串长度
it will fetch the whole file and then calculate the filesize (rather the string length) out of the retrieved data. usually filesize can tell the filesize directly from the filesystem without reading the whole file first.
so this will be rather slow, and will everytime fetch the whole file before being able to retrieve the filesize (string length