|
|
 |
filesize (PHP 3, PHP 4, PHP 5) filesize -- Gets file size Descriptionint 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.
Tip: As of PHP 5.0.0 this function
can also be used with some URL wrappers. Refer to
Appendix L for a listing of which wrappers support
stat() family of functionality.
Example 1. filesize() example |
<?php
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>
|
|
See also file_exists()
User Contributed Notes
filesize
development at lab-9 dot com
28-Apr-2005 11:51
here a small function to retrieve a folder's size recursive :-) I don't know if there is no function that retrieves a folder size or if I was just to dumb to find it :-)
hint: call the function with $output=true if you want to have also a status message where the function read that stuff .. usually you don't need that
<?php
function get_folder_size($target, $output=false)
{
$sourcedir = opendir($target);
while(false !== ($filename = readdir($sourcedir)))
{
if($output)
{ echo "Processing: ".$target."/".$filename."<br>"; }
if($filename != "." && $filename != "..")
{
if(is_dir($target."/".$filename))
{
$totalsize += get_folder_size($target."/".$filename, $exceptions);
}
else if(is_file($target."/".$filename))
{
$totalsize += filesize($target."/".$filename);
}
}
}
closedir($sourcedir);
return $totalsize;
}
$size = get_folder_size("/var/www/html", false);
echo "~".(int)($size/1024)."kb";
?>
greetingz, D.
basslines at gmail dot com
14-Apr-2005 10:14
The function that huda posted below works well enough for small files but if you are trying to find the size of, say, a 60 meg file .. you do not want to download the entire thing every time you are checking the size. Keep this in mind if you want to use it. The best way to do it is to read the content length returned by an HTTP request, hands down.
studioeclection at HAHA dot sbcglobal dot net
13-Apr-2005 10:18
For those that want to find out the size of an image generated by PHP that isn't going to be written to a file and have found that filesize's url wrapper's don't quite work, try this:
$url = "url/to/image/script.php";
$image = file_get_contents($url, 'rb');
$size = strlen($image);
huda m elmatsani
30-Mar-2005 09:08
Are you looking for simpler filesize function for a remote file?
function remoteFilesize($url){
$file = @fopen($url, 'rb');
$buffer = "";
while(!feof($file))
{
$buffer .= fread($file,1024);
}
return strlen($buffer);
}
wesman20 at hotmail dot com
27-Mar-2005 04:30
The human-readable conversion can be done with extreme brevity since it is a logarithmic scale. Feel free to adjust the round() to your own personal tastes.
<?php
function getfilesize($size) {
$units = array(' B', ' KB', ' MB', ' GB', ' TB');
for ($i = 0; $size > 1024; $i++) { $size /= 1024; }
return round($size, 2).$units[$i];
}
?>
php at meteleskublesku dot cz
23-Mar-2005 05:10
YET ANOTHER SIZE FORMATTING ROUTINE (double fixed example from cstretton)
$prec(ision) is the number of important decimal digits in the output, reccomended 3.
<?php
function fmtsize($size, $prec) {
$size = round(abs($size));
$units = array(0=>" B ", 1=>" kB", 2=>" MB", 3=>" GB", 4=>" TB");
if ($size==0) return str_repeat(" ", $prec)."0$units[0]";
$unit = min(4, floor(log($size)/log(2)/10));
$size = $size*pow(2, -10*$unit);
$digi = $prec-1-floor(log($size)/log(10));
$size = round($size*pow(10, $digi))*pow(10, -$digi);
while (strlen($size)<=$prec) $size = " $size";
return $size.$units[$unit];
}
?>
Raphael Kirchner
06-Mar-2005 08:52
Addition to my earlier post: I searched around and found the background in the notes for disk_total_space(): http://www.php.net/manual/en/function.disk-total-space.php
To give a short summary here - andudi pointed out that
a) the SIZE of a file and
b) the SPACE on disk it uses
aren't equal and shalless provided a function dskspace() which returns exactly (tested!) what "du" would.
Raphael Kirchner
06-Mar-2005 08:10
I just tested the dirsize() function posted below by Daniellehr and found out it's not working. I assume it should return the same as the Unix command "du -b" but it doesn't. In my tests it returned some 4.15 MB for a dir that is actually 10.23 MB big, or 302 kB for "real" 220 kB in another one.
And Snoop Baron's fix (inserting $dirName) is none - it just stops it from working recursively.
hervard at gmail com
05-Mar-2005 02:21
Here's a set of functions that will give you a human-readable file size (I didn't write the first function, but I did the second one). compute_size() will take a byte number and spit out an easier-to-read version.
<?php
function truncate_decimals ($num) {
$shift = pow(10, 2);
return ((floor($num * $shift)) / $shift);
}
function compute_size ($byte_number) {
if ($byte_number < 1024) {
return $byte_number.' bytes';
} elseif ($byte_number < 1048576) {
return truncate_decimals($byte_number / (1024)).' KB';
} elseif ($byte_number < 1073741824) {
return truncate_decimals($byte_number / (1048576)).' MB';
} elseif ($byte_number < 1099511627776) {
return truncate_decimals($byte_number / (1073741824)).' GB';
}
}
?>
For example, compute_size(230877) will return "225.46 KB" and compute_size(23935772) will return "22.82 MB". I think I've done the maths right.
snowknight26 AT hotmail DOT com
19-Feb-2005 09:56
To aidan at php dot net:
There is a much easier way of giving so called 'human readable' sizes.
<?php
list($width, $height) = getimagesize($filename);
$imgsize = filesize($filename)/1024;
$imgsize2 = round($imgsize, 0);
echo $imgsize2." KB";
?>
In this case, I divided the filesize of $filename by 1024 since it prints it out in bytes. This will show how many kilobytes it is. It will show something like 152.7123461239461. Thats where rounding comes in hand.
KOmaSHOOTER at gmx dot de
31-Jan-2005 11:16
<?php
function getfilesize($bytes) {
if ($bytes >= pow(2,40)) {
$return = round($bytes / pow(1024,4), 2);
$suffix = "TB";
} elseif ($bytes >= pow(2,30)) {
$return = round($bytes / pow(1024,3), 2);
$suffix = "GB";
} elseif ($bytes >= pow(2,20)) {
$return = round($bytes / pow(1024,2), 2);
$suffix = "MB";
} elseif ($bytes >= pow(2,10)) {
$return = round($bytes / pow(1024,1), 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
if ($return == 1) {
$return .= " " . $suffix;
} else {
$return .= " " . $suffix . "s";
}
return $return;
}
echo getfilesize(pow(2,30));
?>
elonen at iki dot fi
31-Jan-2005 04:40
Shorter version of the file size pretty-printing function:
function human_format_size( $bytes )
{
$formats = array("%d Bytes", "%.1f KB", "%.1f MB", "%.1f GB", "%.1f TB");
$logsize = min((int)(log($bytes)/log(1024)), count($formats)-1);
return sprintf( $formats[$logsize], $bytes/pow(1024, $logsize));
}
Snoop Baron
24-Jan-2005 04:55
A small fix to the function bellow. Changed "is_dir($file) to is_dir("dirName$file"):
<?php
function dirsize($dirName = '.') {
$dir = dir($dirName);
$size = 0;
while($file = $dir->read()) {
if ($file != '.' && $file != '..') {
if (is_dir("$dirName$file")) {
$size += dirsize($dirName . '/' . $file);
} else {
$size += filesize($dirName . '/' . $file);
}
}
}
$dir->close();
return $size;
}
?>
Daniellehr [-AT-] gmx [-DOT-] de
15-Jan-2005 04:48
To find out the size of a folder you can use this recursive-working function:
<?php
function dirsize($dirName = '.') {
$dir = dir($dirName);
$size = 0;
while($file = $dir->read()) {
if ($file != '.' && $file != '..') {
if (is_dir($file)) {
$size += dirsize($dirName . '/' . $file);
} else {
$size += filesize($dirName . '/' . $file);
}
}
}
$dir->close();
return $size;
}
?>
Have fun
Daniel Lehr aka titus
cstretton at gmail dot com
26-Dec-2004 03:30
The function below doesn't work properly for files below 1kb, heres a fixed one.
<?php
function getfilesize($bytes) {
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
if ($return == 1) {
$return .= " " . $suffix;
} else {
$return .= " " . $suffix . "s";
}
return $return;
}
?>
Daijoubu
19-Nov-2004 07:56
It should be URL and not URI ;)
Here's my function for retrieving remote filesize without for peoples without CURL (no auth/302 Found support)
Return the int filesize or false on failure
<?php
function filesize_remote($url, $timeout=2)
{
$url = parse_url($url);
if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout))
{
fwrite($fp, 'HEAD '.$url['path'].$url['query']." HTTP/1.0\r\nHost: ".$url['host']."\r\n\r\n");
stream_set_timeout($fp, $timeout);
while (!feof($fp))
{
$size = fgets($fp, 4096);
if (stristr($size, 'Content-Length') !== false) {
$size = trim(substr($size, 16));
break;
}
}
fclose ($fp);
}
return is_numeric($size) ? intval($size) : false;
}
?>
bkimble at ebaseweb dot com
19-Nov-2004 05:33
In addition to the handy function Kris posted, here is an upgraded version that does basic http authentication as well.
<?php
function remote_filesize($uri,$user='',$pw='')
{
ob_start();
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
if (!empty($user) && !empty($pw))
{
$headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$okay = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $head, $matches);
if (isset($matches[1]))
{
$size = $matches[1];
}
else
{
$size = 'unknown';
}
return $size;
}
?>
aidan at php dot net
25-Sep-2004 07:45
07-Sep-2004 04:23
For the people that keep asking how to get the filesize for a remote file, i figured this little thing out utilizing curl.
Hope this helps someone
Kris.
<?php
function remote_filesize($uri)
{
ob_start();
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
$okay = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $head, $matches);
if (isset($matches[1]))
{
$size = $matches[1];
} else {
$size = 'unknown';
}
return $size;
}
?>
stoneweg at gmx dot de
23-Feb-2003 07:09
if you don't want to use filesize (for example, because you just have the file-handle):
<?php
fseek($handle, 0, SEEK_END);
$length = ftell($handle);
?>
| |