note 106426 deleted from function.filesize by dave
| From: | dave@php.net | Date: | Thu, 10 Nov 2011 08:06:35 +0000 |
| Subject: | note 106426 deleted from function.filesize by dave | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-184368@lists.php.net to get a copy of this message | ||
Note Submitter: MarkAgius at markagius dot co dot uk
----
filesize($filename) dose not return the file size but the number of characters in the file.
EG.
A file of two lines with 10 characters would be displayed as;
1234567890
1234567890
But filesize() would see it as;
12345678901234567890
filesize() would return a value of 20 characters and not 24 bytes. (As chr 10 and chr 13 at the end
of each line is not counted)
Windows Explorer would display the same file on your hard drive as 24 bytes.
To fix this bug and return the file size use the following code that;
1: Reads the number of characters in the file with filesize(),
2: Reads the number of lines
and returns filesize() + (lines *2)
lines x 2 as we are adding two bytes for each line. (Chr 10 and 13)
function GetFileSize($filepath){
// Return the size of $fileURL
if(!file_exists($fileURL)){
return -1; // Not found error value.
}
// Next line returns number of characters in the file and not the size.
// return filesize($fileURL); // Old code returns number of characters only.
// New code returns the file size in bytes.
$charsInFile = filesize($fileURL);
$fileLines = file($fileURL);
$totalLines = count($fileLines);
$sizeInBytes = $charsInFile+($totalLines*2);
return $sizeInBytes;
}