filesize(): size of a specified file in bytes

The file name is given as input and we can get the size of the file in bytes by using filesize function in PHP
echo filesize('test.htm');
Output is
130

Size of all files of directory

Here is an example to display all files sizes along with the file name of current directory. We used scandir function to list all the files.
$ar=scandir('.'); // current dir
while (list ($key, $val) = each ($ar)) { 
echo $val . filesize($val). " bytes " ;
echo "<br>";
}

Handling Non-Existent Files with filesize()

More on file_exists()
if (!file_exists('sample.txt')) {
    echo 'File does not exist';
} else {
    echo 'File size: ' . filesize('sample.txt') . ' bytes';
}

Example: Convert Bytes to KB, MB, GB Automatically

function format_size($size) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $unit_index = 0;
    while ($size >= 1024 && $unit_index < count($units) - 1) {
        $size /= 1024;
        $unit_index++;
    }
    return round($size, 2) . ' ' . $units[$unit_index];
}

$file_size = filesize('sample.txt');
echo 'Formatted size: ' . format_size($file_size);

Use Case: Handling Multiple File Sizes in a Directory

More on Scandir()
$dir = 'path/to/directory';
$files = scandir($dir);
foreach ($files as $file) {
    if (is_file("$dir/$file")) {
        echo "$file: " . filesize("$dir/$file") . " bytes
"; } }

Example: Using filesize() with a Remote URL

$url = 'http://example.com/sample.jpg';
$headers = get_headers($url, 1);
if (isset($headers['Content-Length'])) {
    echo 'File size: ' . $headers['Content-Length'] . ' bytes';
} else {
    echo 'Unable to determine file size.';
}

Example: Checking File Size in a Different Directory

$file_path = '/var/www/html/sample.txt';
if (file_exists($file_path)) {
    echo 'File size: ' . filesize($file_path) . ' bytes';
} else {
    echo 'File does not exist';
}

Example: Handling Large Files

$file_path = 'large_file.zip';
if (file_exists($file_path)) {
    $file_size = filesize($file_path);
    echo $file_size > 1_000_000 ? 'File size is greater than 1MB' : 'File size is less than 1MB';
} else {
    echo 'File does not exist';
}


File Deleting File Checking if file exists before deleting
PHP
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer