spacer
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

filetypespacer spacer fileperms
[edit] Last updated: Fri, 15 Mar 2013

view this page in

filesize

(PHP 4, PHP 5)

filesizeGets file size

Description

int filesize ( string $filename )

Gets the size for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 filesize() example

<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename 'somefile.txt';
echo 
$filename ': ' filesize($filename) . ' bytes';

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • file_exists() - Checks whether a file or directory exists



filetypespacer spacer fileperms
[edit] Last updated: Fri, 15 Mar 2013
 
spacer add a note User Contributed Notes filesize - [13 notes]
up
down
1
Supermagnus
4 years ago
<?php
function getSizeFile($url) {
    if (
substr($url,0,4)=='http') {
       
$x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
        if (
strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
        else {
$x = $x['content-length']; }
    }
    else {
$x = @filesize($url); }

    return
$x;
}
?>

In case of you have a redirection in the server (like Redirect Permanent in the .htaccess)

In this case we have for exemple:
    [content-length] => Array

        (

            [0] => 294          // Size requested file

            [1] => 357556     // Real Size redirected file

        )
up
down
1
core58 at mail dot ru
6 years ago
some notes and modifications to previous post.
refering to RFC, when using HTTP/1.1 your request (either GET or POST or HEAD) must contain Host header string, opposite to HTTP/1.1 where Host ain't required. but there's no sure how your remote server would treat the request so you can add Host anyway (it won't be an error for HTTP/1.0).
host value _must_ be a host name (not CNAME and not IP address).

this function catches response, containing Location header and recursively sends HEAD request to host where we are moved until final response is met.
(you can experience such redirections often when downloading something from php scripts or some hash links that use apache mod_rewrite. most all of dowloading masters handle 302 redirects correctly, so this code does it too (running recursively thru 302 redirections).)

[$counter302] specify how much times your allow this function to jump if redirections are met. If initial limit (5 is default) expired -- it returns 0 (should be modified for your purposes whatever).0
ReadHeader() function is listed in previous post
(param description is placed there too).

<?php
function remote_filesize_thru( $ipAddress, $url, $counter302 = 5 )
{
   
$socket = fsockopen( "10.233.225.2", 8080 );
    if( !
$socket )
    {
       
// failed to open TCP socket connection
        // do something sensible here besides exit();
       
echo "<br>failed to open socket for [$ipAddress]";
        exit();
    }
                   
   
// just send HEAD request to server
   
$head = "HEAD $url HTTP/1.0\r\nConnection: Close\r\n\r\n";
   
// you may use HTTP/1.1 instead, then your request head string _must_ contain "Host: " header
   
fwrite( $socket, $head );
       
   
// read the response header
   
$header = ReadHeader( $socket );
    if( !
$header )
    {
       
// handle empty response here the way you need...
       
Header( "HTTP/1.1 404 Not Found" );
        exit();
    }
   
   
fclose( $socket );
   
   
// check for "Location" header
   
$locationMarker = "Location: ";
   
$pos = strpos( $header, $locationMarker );
    if(
$pos > 0 )
    {
           
$counter302--;
            if(
$counter302 < 0 )
            {
                    
// redirect limit (5 by default) expired -- return some warning or do something sensible here
                   
echo "warning: too long redirection sequence";
                    return
0;
            }

           
// Location is present -- we should determine target host and move there, like any downloading masters do...
            // no need to use regex here
           
$end = strpos( $header, "\n", $pos );
           
$location = trim( substr( $header, $pos + strlen( $locationMarker ), $end - $pos - strlen( $locationMarker ) ), "\\r\\n" );
            
            
// extract pure host (without "")
            
$host = explode( "/", $location );
            
$ipa = gethostbyname( $host[2] );
            
// move to Location
            
return remote_filesize_thru( $ipa, $location, $counter302 );
    }
       
   
// try to acquire Content-Length within the response
   
$regex = '/Content-Length:\s([0-9].+?)\s/';
   
$count = preg_match($regex, $header, $matches);
                       
   
// if there was a Content-Length field, its value
    // will now be in $matches[1]
   
if( isset( $matches[1] ) )
         
$size = $matches[1];
    else
         
$size = 0;
   
    return
$size;
}
?>
up
down
3
Anonymous
2 years ago
if you recently appended something to file, and closed it then this method will not show appended data:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
You should insert a call to clearstatcache() before calling filesize()
I've spent two hours to find that =/
up
down
8
rommel at rommelsantor dot com
1 year ago
Extremely simple function to get human filesize.
<?php
function human_filesize($bytes, $decimals = 2) {
 
$sz = 'BKMGTP';
 
$factor = floor((strlen($bytes) - 1) / 3);
  return
sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>
up
down
0
frank (at) haua dot net
2 years ago
I have a cli script running that use the filesize function on a ssh2_sftp connection. It has the >2Gb limit issue, while it does not have that issue locally. I have managed to get around this by doing a "du -sb" command through ssh2_shell.

The following function takes the ssh2_connect resource and the path as input. It may not be neat, but it solves the problem for the moment.

<?php
function fSSHFileSize($oConn, $sPath) {
    if(
false !== ($oShell = @ssh2_shell($oConn, 'xterm', null, 500, 24, SSH2_TERM_UNIT_CHARS))) {
       
fwrite($oShell, "du -sb '".$sPath."'".PHP_EOL);
       
sleep(1);
        while(
$sLine = fgets($oShell)) {
           
flush();
           
$aResult[] = $sLine;
        }
       
fclose($oShell);
       
$iSize = 0;
        if(
count($aResult) > 1) {
           
$sTemp = $aResult[count($aResult)-2];
           
$sSize = substr($sTemp, 0, strpos($sTemp, chr(9)));
            if(
is_numeric(trim($sSize))) {
               
$iTemp = (int)$sSize;
                if(
$iTemp > "2000000000") $iSize = $iTemp;
            }
        }
        return
$iSize;
    }
    return
0;
}
?>
up
down
0
Svetoslav Marinov
3 years ago
This is an updated version of my previous filesize2bytes.
The return type now it's really an int.

<?php
/**
 * Converts human readable file size (e.g. 10 MB, 200.20 GB) into bytes.
 *
 * @param string $str
 * @return int the result is in bytes
 * @author Svetoslav Marinov
 * @author slavi.biz
 */
function filesize2bytes($str) {
   
$bytes = 0;

   
$bytes_array = array(
       
'B' => 1,
       
'KB' => 1024,
       
'MB' => 1024 * 1024,
       
'GB' => 1024 * 1024 * 1024,
       
'TB' => 1024 * 1024 * 1024 * 1024,
       
'PB' => 1024 * 1024 * 1024 * 1024 * 1024,
    );

   
$bytes = floatval($str);

    if (
preg_match('#([KMGTP]?B)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
       
$bytes *= $bytes_array[$matches[1]];
    }

   
$bytes = intval(round($bytes, 2));

    return
$bytes;
}
?>
up
down
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.