Skip to content

PHP Tutorial File Handling

File Information

Lesson 170 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

PHP can tell you a lot about a file without opening it.

Size and dates

index.php
PHP
<?php
file_put_contents("report.txt", "Quarterly numbers");

echo filesize("report.txt") . " bytes\n";
echo date("Y", filemtime("report.txt")) === date("Y") ? "modified this year" : "older";
Output
OUTPUT
17 bytes
modified this year
  • filesize($file): size in bytes.
  • filemtime($file): last modified time, as a Unix timestamp.
  • fileatime() and filectime(): last access and last change of the file’s metadata.

Name, folder and extension

index.php
PHP
<?php
$path = "/var/uploads/2026/photo.final.JPG";

print_r(pathinfo($path));

echo strtolower(pathinfo($path, PATHINFO_EXTENSION));
Output
OUTPUT
Array
(
    [dirname] => /var/uploads/2026
    [basename] => photo.final.JPG
    [extension] => JPG
    [filename] => photo.final
)
jpg

pathinfo() works on a string. It does not look at the real file.

A readable size

index.php
PHP
<?php
function humanSize(int $bytes): string
{
    $units = ["B", "KB", "MB", "GB"];
    $i = 0;

    while ($bytes >= 1024 && $i < count($units) - 1) {
        $bytes /= 1024;
        $i++;
    }

    return round($bytes, 1) . " " . $units[$i];
}

echo humanSize(900) . "\n";
echo humanSize(5242880) . "\n";
echo humanSize(1610612736);
Output
OUTPUT
900 B
5 MB
1.5 GB

The real file type: finfo

The extension is only a name. A file called photo.jpg might contain anything. To find out what the content really is, use the finfo class (the fileinfo extension).

index.php
PHP
<?php
// the smallest valid PNG image
$png = base64_decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==");
file_put_contents("fake.jpg", $png);   // a PNG pretending to be a JPG

$finfo = new finfo(FILEINFO_MIME_TYPE);

echo $finfo->file("fake.jpg");
Output
OUTPUT
image/png

The name says .jpg, but the content is a PNG. finfo looks at the bytes, so you cannot be fooled by a rename. You will use this in Secure File Uploads.

Image size

index.php
PHP
<?php
$png = base64_decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==");
file_put_contents("tiny.png", $png);

[$width, $height] = getimagesize("tiny.png");

echo "$width x $height";
Output
OUTPUT
1 x 1

getimagesize() also returns false if the file is not a valid image, which makes it a useful extra check.

Clear the file status cache

PHP caches some results (filesize, file_exists) during one script. If the file changes while the script runs, call clearstatcache() before checking again.

lightbulb
Do not trust extensions
Use pathinfo() for the name, and finfo for what the file really is.