Page 1 of 1

Get file size on remote file

Posted: Wed Aug 27, 2008 12:30 am
by aliasxneo
Is it possible to get the size of a remote file? E.g:

Code: Select all

<?php
 
$file = "http://www.mysite.com/file.zip";
 
$size = getRemoteSize($file); // How to get the size?
 
?>
Anyone know how?

Regards,
Josh

Re: Get file size on remote file

Posted: Wed Aug 27, 2008 5:56 am
by Ziq
Is it possible to get the size of a remote file?
Yes. If you want to do this you should use sockets. And you should know HTTP specification.

This code help you to know remote filesize.

Code: Select all

 
<?php
function get_size( $url )
{
    // ???????? ?? ?? ???????????? 
    $url = parse_url($url); 
    $host = $url['host'];
    $path = $url['path']; 
    $port = isset($url['port'])? $url['port'] : 80; 
 
    if(isset($url['query']))           
        $path .= '?' . $url['query']; 
 
        
    if(!($f = fsockopen($host, $port, $ern, $ers))) 
        die("Cannot connect to $host: Error #$ern ($ers)"); 
 
    fputs($f, "HEAD $path HTTP/1.0\r\nHOST: $host\r\n\r\n"); 
 
    
    for($reply = ''; !feof($f); )  $reply .= fgets($f); 
    fclose($f); 
 
 
    
    if(!preg_match("|^HTTP/[\d]+\.[\d]+[\s]+200[\s]|i", $reply)) 
        { $lines= explode("\n", $reply); echo $lines[0]; } 
    else         
        if(preg_match("|\nContent-length:[\s]+([\d]+)|i", $reply, $res)) 
            echo "File $nm is ${res[1]} bytes length\r\n"; 
        else  
            echo "Cannot detect length of file $path\r\n<pre>" 
                 .htmlspecialchars($reply)."</pre>"; 
} 
get_size($_GET['url']);
?> <form><input name=url size=40 
     value = "http://forums.devnetwork.net/styles/subsilver2/imageset/site_logo.gif" /> 
     <input type=submit value=size? /> </form> 
 

Re: Get file size on remote file

Posted: Wed Aug 27, 2008 10:20 pm
by aliasxneo
Thanks but I found a better method:

Code: Select all

$headers = get_headers($url, 1);
$length = $headers['Content-Length'];
For anyone else interested.