PHP:获得远程文件大小吗? (html) [英] PHP: get remote file size with strlen? (html)

查看:61
本文介绍了PHP:获得远程文件大小吗? (html)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找fsockopen和其他内容的PHP文档,他们说您不能在不使用ftell或某些东西疯狂地做某事的情况下(不能确切地说他们说的是什么)在远程文件上使用filesize(),但是我有一个关于如何做的好主意:

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.

推荐答案

此答案需要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).

<?php
echo get_remote_size("http://www.google.com/");

function get_remote_size($url) {
    $headers = get_headers($url, 1);
    if (isset($headers['Content-Length'])) return $headers['Content-Length'];
    if (isset($headers['Content-length'])) return $headers['Content-length'];

    $c = curl_init();
    curl_setopt_array($c, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => array('User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3'),
        ));
    curl_exec($c);
    return curl_getinfo($c, CURLINFO_SIZE_DOWNLOAD);
}
?>

这篇关于PHP:获得远程文件大小吗? (html)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆