PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<filepermsfiletype>
view the version of this page
Last updated: Thu, 21 Aug 2003

filesize

(PHP 3, PHP 4 )

filesize -- Gets file size

Description

int filesize ( string filename)

Returns the size of the file in bytes, or FALSE in case of an error.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, filesize() may return unexpected results for files which are larger than 2GB. For files between 2GB and 4GB in size this can usually be overcome by using sprintf("%u", filesize($file)).

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

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

Example 1. filesize() example

<?php

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

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

?>

See also file_exists()



add a note add a note User Contributed Notes
filesize
mehdi at ill dot iut dot ac dot ir
26-Oct-2003 10:42
this function returns human-readable filesizes whether or not they are directories or regular files.

function fsize($file){
        $size=0;
        $range = Array ('B', 'K', 'M', 'G');

        if(is_dir($file))
                if ($dh = opendir($file)){
                        while (($filecnt = readdir($dh)) !== false) {
                                if($filecnt == "." || $filecnt == "..")continue;
                                if(is_dir($file."/".$filecnt))
                                        $size += fsize($file."/".$filecnt);
                                else
                                        $size += filesize($file."/".$filecnt);
                                echo "\n$file/$filecnt";
                        }
                        closedir($dh);
                }else
                        return false;
        else
                $size = filesize($file);

        for ($i = 0; $size >= 1024 && $i < count($range); $i++)
                $size /= 1024;

        return round($filesize,2).$range[$i];
}

also in linux like systems you can use :
$size = exec("du -sh $file");
mehdi at ict dot iut dot ac dot ir
26-Oct-2003 08:23
this function returns the size of $file whether or not it is a directory.

function fsize($file){
        $size;

        if(is_dir($file))
                if ($dh = opendir($file))
                        while (($filecnt = readdir($dh)) !== false) {
                                if($filecnt == "." || $filecnt == "..")continue;
                                if(is_dir($file."/".$filecnt))
                                        $size += fsize($file."/".$filecnt);
                                else
                                        $size += filesize($file."/".$filecnt);
                        }
                else
                        return false;
        else
                $size = filesize($file);
        return $size;
}
let at turx dot org
31-Jul-2003 09:58
this function returns filesize in kilobytes seperated with commas for every thousand.

function fsize($file) {
      return number_format(filesize($file)/1024)." KB";
}

simple & effective.
anbolb at boltblue dot com
13-May-2003 05:15
re a human-readable filesize function, PHP remembers the variable you set up in a for loop, so you could just do something like this:

    $type = Array ('bytes', 'kilobytes', 'megabytes', 'gigabytes');
    $filesize = filesize ($filename);

    for ($i = 0; $filesize > 1024; $i++)
        $filesize /= 1024;

    return round ($filesize, 2)." $type[$i]";
dave at birko dot cjb dot net
31-Mar-2003 08:53
I saw some filesize -> human readable "translation routines" here...
Well, check this out, php-"coders" ;)
See ya.

function fsize($file) {
        $a = array("B", "KB", "MB", "GB", "TB", "PB");

        $pos = 0;
        $size = filesize($file);
        while ($size >= 1024) {
                $size /= 1024;
                $pos++;
        }

        return round($size,2)." ".$a[$pos];
}
gt at realvertex dot com
19-Mar-2003 01:53
If you are using filesize($file), and $file variable is passed by using the function file(), then first use trim to get rid of the new line at the end of the $file variable.
You could do: filesize(trim($file))
Hope this helps!
pkrumins[catsatonmat]inbox[dope]lv
02-Mar-2003 11:08
here is my function or calculating filesize with a correct argument.

function size($bytes) {
  $types =  Array("bytes","kilobytes","megabytes","gigabytes","terabytes");
   $current = 0;
  while ($bytes > 1024) {
   $current++;
   $bytes /= 1024;
  }
  return round($bytes,2)." ".$types[$current];
}
stoneweg at gmx dot de
23-Feb-2003 09:09
if you don't want to use filesize (for example, because you just have the file-handle):

fseek($handle, 0, SEEK_END);
$length = ftell($handle);
swbrown at ucsd dot edu
14-Feb-2003 10:35
Be very careful to include clearstatcache() before any call to filesize()!  I just finished debugging a really painful bug to find that was due to reading in a file like 'fread($file, filesize(...))', writing it out, then later reading it in the same way.  filesize() was cached, so in some cases, the data was truncated!
E dot A dot M dot Huijbers at student dot tue dot nl
06-Feb-2003 09:03
filesize() returns a 32-bit (signed) value. This means that it will return a negative value for files between 2Gb and 4Gb (which can still be corrected with a little math), and will return an outright incorrigible value for files larger than 4Gb.
brodie-php at tmts dot ca
21-Jan-2003 08:20
The following code builds on the some of the above comments.  It reads a directory for a particular file type (.mp3) and then lists the files and their sizes.

In this case, I wanted to put some special mp3s in a directory and be able to add to the list easily without changing the webpage.

<?php 

   
//$imagedir is the absolute path to the directory wherein you wish to store special mp3s

    //example: $imagedir = "/usr/local/www/data/user/dir";
   
   
$imagedir "C:/Windows/User/Dir"//current directory
   
   
$i 1;
   
    if (
$handle opendir("$imagedir")) {
        while (
false !== ($file readdir($handle))) { 
           
//strncmp returns < 0 if arg1 is less, >0 if more, 0 if equal
           
$extension substr($file, -44);
            if (
$file != "." && $file != ".." && ($extension == ".mp3")) {
                echo(
$i++.".&nbsp;&nbsp; <a href=\"$file\">$file (".fsize($file).")</a><br>");
            } 
        }
       
closedir($handle); 
    }else{
        echo(
"<br>Directory could not be opened.<br>");
    }

function 
fsize($file) {
   
   
// Does the file exist?
   
if(is_file($imagedir.$file)){
       
       
//Setup some common file size measurements.
       
$kb=1024;
       
$mb=1048576;
       
$gb=1073741824;
       
$tb=1099511627776;
       
       
//Get the file size in bytes.
       
$size filesize($file);
       
       
//Format file size
       
       
if($size $kb) {
        return 
$size." B";
        }
        else if(
$size $mb) {
        return 
round($size/$kb,2)." KB";
        }
        else if(
$size $gb) {
        return 
round($size/$mb,2)." MB";
        }
        else if(
$size $tb) {
        return 
round($size/$gb,2)." GB";
        }
        else {
        return 
round($size/$tb,2)." TB";
        }
    }
}
?>
dmitri926 AT yahoo DOT com
07-Jan-2003 10:08
i created function dir_size, it finds out the size of files in a directory and its subdirectories using recursion. it returns the total size in bytes.

function dir_size($dir) {
    $totalsize=0;
    if ($dirstream = @opendir($dir)) {
        while (false !== ($filename = readdir($dirstream))) {
            if ($filename!="." && $filename!="..")
            {
                if (is_file($dir."/".$filename))
                    $totalsize+=filesize($dir."/".$filename);
               
                if (is_dir($dir."/".$filename))
                    $totalsize+=dir_size($dir."/".$filename);
            }
        }
    }
    closedir($dirstream);
    return $totalsize;
}
thebitman at attbi dot com
05-Jan-2003 11:52
Though the above-posted method for getting the remote file size is probably the fastest, this improvement to x@x.com's method is a lot faster than the original:

function remotefiletoobig($file,$maxbytes) {
// $maxbytes; // in bytes

// Open the file, but only read maximum size
$fp = fopen($file, "r");
$first_file_size_read = fread($fp, $maxbytes + 1);
fclose($fp);

return (strlen($first_file_size_read) > $maxbytes);
}
will at deepbass dot com
18-Dec-2002 07:44
there's a function for getting the size of a remote file here:

http://www.iezzi.ch/snippets/003_fsize.php
g_adams27 at hotmail dot com
28-Nov-2002 01:43
For Windows users, note that when the manual says "this function will not work on remote files", that also includes other drive partitions on the same computer.

In my case (Win2K/IIS 5/PHP 4.2.1), I had PHP and the webserver running on E:\ , but was trying to create, write to, and then run filesize() on some temporary files in C:\WINNT\Temp .  filesize() kept telling me it couldn't stat the temporary files.  Once I finally realized what was going on, I moved the location of the temporary files to E:\Temp, and everything worked like a charm.
PHPMatrix
13-Oct-2002 07:25
I found this nice little human readable file size code.  It seems simpler and easier to understand.  I'm a PHP newbee so that's why I say its easy to understand.  I don't get the above codes, lol.  Hope it helps some other newbe, lol.

<?php
$my_file 
"/path/to/my/file";
$file_size filesize($my_file);
if (
$file_size >= 1073741824) {
       
$show_filesize number_format(($file_size 1073741824),2) . " GB";
} elseif (
$file_size >= 1048576) {
       
$show_filesize number_format(($file_size 1048576),2) . " MB";
} elseif (
$file_size >= 1024) {
       
$show_filesize number_format(($file_size 1024),2) . " KB";
} elseif (
$file_size >= 0) {
       
$show_filesize $file_size " bytes";
} else {
       
$show_filesize "0 bytes";
}
echo 
"File $my_file is $show_filesize ";
?>

Ryan
cnww at a host called k-pcltee dot com
24-Sep-2002 07:22
A nice short human readable function:
  function human_readable( $number, $base=1024,
    $suffixes=array( " B", " KB", " MB", " GB", " TB", " PB", " EB" )
  )
  {
    $usesuf = 0;
    $n = (float) $number; //Appears to be necessary to avoid rounding
    while( $n >= $base ) {
      $n /= (float) $base;
      $usesuf++;
    }
    $places = 2 - floor( log10( $n ) );
    $places = max( $places, 0 );
    $retval = number_format( $n, $places, ".", "" ) . $suffixes[$usesuf];
    return $retval;
  }
andreaSPAMLESS@SPAMLESScriticalbitDOTcom
05-Jul-2002 06:29
I've just implemented an easy&extensible function for calculating file size in an human readable format.
It does'n check any file, it just formats any given number.

Hope it helps anyone ;)

/**
 * Format file size in a human-readable way
 * such as "xx Megabytes" or "xx Mo"
 *
 * @author           Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
 * @version          1.0
 * @param int       bytes   is the size
 * @param bool      base10  enable base 10 representation, otherwise
 *                  default base 2  is used 
 * @param int       round   number of fractional digits
 * @param array     labels  strings associated to each 2^10 or
 *                  10^3(base10==true) multiple of base units
 */
function hbytes ($bytes, $base10=false, $round=0,
                 $labels=array('bytes', 'Kb', 'Mb', 'Gb')) {
   
    if (($bytes <= 0) ||
        (! is_array($labels)) ||
        (count($labels) <= 0))
        return null;
   
    $step = $base10 ? 3 : 10 ;
    $base = $base10 ? 10 : 2;
   
    $log = (int)(log10($bytes)/log10($base));
   
    krsort($labels);
   
    foreach ($labels as $p=>$lab) {
        $pow = $p * $step;
        if ($log < $pow) continue;
        $text = round($bytes/pow($base,$pow),$round) . $lab;
        break;
    }
   
    return $text;
}

Notice that you can pass any number of labels: the function automatically uses the biggest one available.
E.g.
If you pass only "bytes" , then every file will have it's size printed in bytes.
(almost useless...)

If you add "Kb" , then any filesize bigger than 1Kb will use Kb instead.

Works similarly for any bigger unit until Tera or even Peta bytes :)

Maybe there's some bug I didn't notice (Murphy docet) , so please warn me if it occurs.
andudi at gmx dot ch
12-Jun-2002 06:45
To find the total size of a file/directory you have to differ two
situations:
(on Linux/Unix based systems only!?)

you are interested:
1) in the total size of the files in the dir/subdirs
2) what place on the disk your dir/subdirs/files uses

- 1) and 2) normaly differs, depending on the size of the inodes
- mostly 2) is greater than 1) (in the order of any kB)
- filesize($file) gives 1)
- "du -ab $file" gives 2)

so you have to choose your situation!

on my server I have no rights to use "exec du" in the case of
2), so I use:
  $s = stat($file);
  $size = $s[11]*$s[12]/8);
whitch is counting the inodes [12] times the size of them in Bits [11]

hopes this helps to count the used disk place in a right way... :-)

                     Andreas Dick
sponger
11-Jun-2002 01:28
This may come in handy for someone. Returns the size of the passed file in the appropriate measurement format.

function my_filesize($file) {
    // First check if the file exists.
    if(!is_file("./".$file)) exit("File does not exist!");
    // Setup some common file size measurements.
    $kb = 1024;         // Kilobyte
    $mb = 1048576;      // Megabyte
    $gb = 1073741824;   // Gigabyte
    $tb = 1099511627776;// Terabyte

    // Get the file size in bytes.
    $size = filesize($file);
    /* If it's less than a kb we just return the size, otherwise we keep going until
    the size is in the appropriate measurement range. */
    if($size < $kb) {
        return $size." B";
    }
    else if($size < $mb) {
        return round($size/$kb,2)." KB";
    }
    else if($size < $gb) {
        return round($size/$mb,2)." MB";
    }
    else if($size < $tb) {
        return round($size/$gb,2)." GB";
    }
    else {
        return round($size/$tb,2)." TB";
    }
}
webmaster at tapetky dot cz
27-May-2002 07:45
How many place is free?
How many dirs and files is on my web?

--------------------------------------------
$quota="100"; // place for your web in MB

function obsah($adr,&$total,&$dir,&$size){           
  $dp=OpenDir($adr);

  do{
    $itm=ReadDir($dp);
    if (Is_Dir("$adr/$itm")&&($itm!=".")&&($itm!="..")&&($itm!="")){
      obsah("$adr/$itm",$total,$dir,$size);
      $dir++;
    }
    elseif (($itm!=".")&&($itm!="..")&&($itm!="")){
      $size=$size+FileSize("$adr/$itm");
      $total++;
    }
  } while ($itm!=false);

  CloseDir($dp);
}

obsah(".",$total,$dir,$size);
$freeA=BcDIV($size,1024*1024,2);
$freeB=$quota-$freeA;

echo "<CENTER><FONT FACE=arial SIZE=2>
Engaged place: <B>$freeA</B> MB
Free place: <B>$freeB</B> MB
<B>$total</B> files in <B>$dir</B> dirs
</FONT></CENTER>";
--------------------------------------------
x at x dot com
20-Apr-2002 10:30
If you want to check the size in order to limit the filesize, this should work.

---------------------------------

function remotefilesize($file)
{
    // SETTINGS
    $max_file_size = "1000" // in bytes

    // Open the file, but only read maximum size
    $fp = fopen($file, "r");
    $first_file_size_read = fread($fp, $max_file_size);
    fclose($fp);

    // Open the file plus one byte...
    // if there is an extra byte, then it is too big,
    $fp = fopen("$image", "r");
    $second_file_size_read = fread($fp, $max_file_size + 1);
    fclose($fp);

    // Check if they're the same
    if ($first_file_size_read == $second_file_size_read)
    {
        $file_size_ok == "yes";
    }
}

--------------------------------

What you do with $file_size_ok is up to you after this.

This should work, but it's a dirty hack.

Good luck!
mufasa at firetiger dot net
30-Jan-2002 06:25
NOTE: The filesize() function will report the usuall PHP run-time error _in addition to_ returning false if it can't find the file. I assume any error with this function will report an error too, but I've only tested for the file not found condition.

If you're expecting or allowing the script to go on after any such error, just add the @ symbol before it to ignore the error. As always with the @ symbol though, still check any variables that were expected to have a value in them from this function before you use them.

<filepermsfiletype>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST