PHP: get remote file size using strlen? (HTML)

I looked at the PHP docs for fsockopen and whatnot, and they say that you cannot use filesize () in the remote file without doing some crazy things with ftell or something (not sure what they said for sure), but I had a good thought on how to do this:

$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 was so simple and useful to use at that time, I just want to get any thoughts if this might run into problems or not be the true file size.

I want to use this only by text (websites), not binary.

+2
source share
3 answers

PHP5 cUrl. . Content-Length , cUrl ( , - ).

<?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);
}
?>
+5

get_headers(). HTTP- HTTP-. Content-length , .

curl streams, HEAD GET. Content-length , . .

+3

, ( ) . , .

so it will be rather slow and will extract the whole file each time before being able to get the file size (line length

0
source

Source: https://habr.com/ru/post/1768707/


All Articles