PHP: Sorting Files by Size

Updated: January 11, 2024 By: Guest Contributor Post a comment

Introduction

Handling files is a common operation in many web applications. It’s often required to sort these files based on various attributes such as name, date, type, and size. In this tutorial, we’re going to concentrate on how to sort files by size in PHP, a popular server-side scripting language.

Sorting files by size can be particularly useful when you want to organize uploads, manage storage, or allow users to view files in a directory by their size. PHP offers multiple functions to get file size and to sort arrays, which makes it possible to combine these capabilities to sort files by their size easily.

Getting Started

Before we dive into the code, let’s make sure that you have a PHP environment set up. You can use a local server like XAMPP, WAMP, or MAMP or a remote server where PHP is installed and running. For file operations, it’s important to check the directory permissions to ensure that PHP scripts have read access to the files you want to sort.

Fetch the List of Files

To sort the files, we first need to fetch the list of files from the directory we are interested in. PHP’s scandir() function will be used for this purpose.

$directory = 'path/to/your/files';
$files = scandir($directory);

The scandir() function returns an array of filenames found within the specified directory. By default, this array includes . and .., representing the current and parent directories, respectively. If you want to exclude these, you can loop through the results and remove them.

Determine File Sizes

Next, we move on to determine the size of these files. The filesize() function in PHP will help with this. This function returns the size of the file in bytes.

$fileSizes = array();
foreach ($files as $file) {
    if (is_file("$directory/$file")) {
        $fileSizes[$file] = filesize("$directory/$file");
    }
} 

Here, we are using the is_file() function to ensure that we are dealing with files and not directories. We construct an associative array where keys are filenames and values are file sizes in bytes.

Sort the Array by File Size

PHP arrays can be sorted in a few different ways. For sorting the array by its values while preserving keys, we will utilize the asort() or arsort() function. The former sorts in ascending order, whereas the latter sorts in descending order.

asort($fileSizes); // For ascending order
// or
arsort($fileSizes); // For descending order

After executing the sort function, $fileSizes array will be sorted by file size.

Display the Sorted Files

Now that we have the sorted array, we can loop through $fileSizes to display the filenames and their corresponding sizes.

foreach ($fileSizes as $file => $size) {
    echo "File: $file - Size: $size bytes<br/>";
}

If you need a more human-readable file size (KB, MB, GB), you can create a function that converts bytes to the desired format:

function formatSizeUnits($bytes) {
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }

    return $bytes;
}

foreach ($fileSizes as $file => $size) {
    echo "File: $file - Size: " . formatSizeUnits($size) . "<br/>";
}

With these pieces of code, you’ve achieved a fully functional script to sort files by size.

Error Handling & Additional Check

When working with files, always include error handling. Use try-catch blocks to catch exceptions when the directory is not readable, or files sizes cannot be retrieved.

Below is an example PHP script that sorts files in a specified directory by their size. It includes error handling to deal with potential issues like unreadable directories or inaccessible file sizes.

<?php

$directoryPath = 'path/to/your/directory'; // Replace with your directory path

try {
    // Check if the directory exists and is readable
    if (!is_dir($directoryPath) || !is_readable($directoryPath)) {
        throw new Exception("Directory does not exist or is not readable: $directoryPath");
    }

    // Scanning files in the directory
    $files = scandir($directoryPath);
    if (!$files) {
        throw new Exception("Failed to scan directory: $directoryPath");
    }

    // Remove '.' and '..' from the list of files
    $files = array_diff($files, array('.', '..'));

    // Create an associative array to hold file sizes
    $fileSizes = [];
    foreach ($files as $file) {
        $filePath = $directoryPath . DIRECTORY_SEPARATOR . $file;
        if (is_file($filePath)) {
            $fileSizes[$file] = filesize($filePath);
        }
    }

    // Sort files by size
    asort($fileSizes);

    // Display sorted files
    foreach ($fileSizes as $file => $size) {
        echo "File: $file, Size: $size bytes\n";
    }
} catch (Exception $e) {
    // Handle exceptions
    echo "Error: " . $e->getMessage();
}

?>

In this script:

  • It checks if the specified directory exists and is readable.
  • Files are scanned in the directory using scandir().
  • Special entries like ‘.’ and ‘..’ are removed from the file list.
  • It creates an associative array where file names are keys, and their sizes are values.
  • The array is sorted by size using asort().
  • It uses a try-catch block to handle exceptions that might occur during the file operations.

Note:

  • Replace 'path/to/your/directory' with the actual path of your directory.
  • This script assumes the directory contains only files. If the directory contains subdirectories, additional checks should be implemented

Conclusion

In this guide, we covered how to sort files by size in PHP. Given that file management is a critical aspect of web development, PHP provides robust tools for handling file-related operations – from scanning directories to sorting files by attributes such as size. With good practices around error handling and performance, you can ensure that your PHP file sorting operations work efficiently and reliably.