Get file size on remote file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

Get file size on remote file

Post 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
User avatar
Ziq
Forum Contributor
Posts: 194
Joined: Mon Aug 25, 2008 12:43 am
Location: Russia, Voronezh

Re: Get file size on remote file

Post 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> 
 
aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

Re: Get file size on remote file

Post 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.
Post Reply