PHP: How to bulk rename files based on a pattern

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

Introduction

Handling files in PHP is a task that developers often encounter. Sometimes, you may discover that you need to rename a large batch of files all at once, which can be quite monotonous and time-consuming if done manually. Fortuitously, PHP provides powerful functions that allow you to automate this process. This tutorial will guide you through the process of bulk renaming files based on a specified pattern using PHP.

Before we jump into coding, let’s discuss some situations where bulk renaming might be necessary. You may need to standardize the naming convention of images for a website, update filenames to include a specific date for archival purposes, or even change extensions as part of a migration process. PHP’s built-in functions like glob(), rename(), and others come in very handy for these types of operations.

Setting Up the Environment

For this tutorial, you’ll need a PHP environment set up. Most modern operating systems have PHP installed by default, or you can install it through various PHP distributions or packages like XAMPP for Windows, MAMP for macOS, or native packages in Linux distributions. Furthermore, you’ll also need a directory with some files that we can use for renaming.

Understanding the Pattern

First, you’ll have to determine the pattern for renaming your files. Patterns can be created using different parts of the existing filename or completely new templates. For example:

  • Add a prefix/suffix to filename: image-123.jpg to modified-image-123.jpg
  • Change numbering format: image1.jpg to image001.jpg
  • Replace spaces with underscores: my family photo.png to my_family_photo.png

Listing Files with glob()

In PHP, the glob() function helps us to find files and directories matching a specific pattern. This will help us to fetch all the files we wish to rename:

$files = glob('path/to/your/files/*.*');
// This will return an array with all the files in the given path.

We can now iterate over this array and perform the renaming process.

Renaming the Files

The rename() function in PHP allows you to rename a file. This function requires two parameters: the current filename and the new filename:

foreach ($files as $file) {
    // Create the new filename ...
    $newFilename = 'new_pattern_' . basename($file);
    // Rename the file
    rename($file, 'path/to/your/files/' . $newFilename);
}

It is crucial to handle filename collisions where the new filename might already exist. We can check before renaming if the new filename exists and handle the scenario accordingly.

Handling Filename Collisions

To avoid overwriting an existing file, we need to check if the new filename already exists:

foreach ($files as $file) {
    $newFilename = 'new_pattern_' . basename($file);
    if (!file_exists('path/to/your/files/' . $newFilename)) {
        rename($file, 'path/to/your/files/' . $newFilename);
    } else {
        // Handle the collision or log it
    }
}

This simple check ensures that you’re not going to overwrite any existing files unintentionally.

Putting It All Together

Now let’s create a small script that puts together what we learned above:

$files = glob('path/to/your/files/*.*');

foreach ($files as $file) {
    // Assume we want to add a date prefix based on file modification time
    $datePrefix = date('Ymd', filemtime($file));
    $newFilename = $datePrefix . '_' . basename($file);

    if (!file_exists('path/to/new/directory/' . $newFilename)) {
        rename($file, 'path/to/new/directory/' . $newFilename);
    } else {
        // Log the collision or take another action
    }
}

This script will attach a date prefix to all files in the specified directory depending on the file modification time and move them to a new directory, given the directory exists and is writable. Ensure you have the appropriate permissions to perform these actions.

Advanced Pattern-based Renaming

More complex renaming schemes can be defined using regular expressions. PHP functions like preg_match() and preg_replace() are used to match and replace patterns respectively:

foreach ($files as $file) {
    // Define the pattern for the current filename
    $pattern = '/^(prefix_)?(.*)(\.jpg)$/';
    // Define the replacement
    $replacement = 'newprefix_$2$3';
    if (preg_match($pattern, basename($file))) {
        $newFilename = preg_replace($pattern, $replacement, basename($file));
        // Proceed with renaming
    }
}

In this example, we are renaming JPG files that may or may not start with ‘prefix_’, adding ‘newprefix_’ instead.

Conclusion

This guide has demonstrated how to rename files in bulk using PHP. Knowing how to handle files effectively with PHP can save time and avoid repetitive tasks. Remember to always create backups before running such operations, and test them on a few files before scaling up. By using PHP’s native functions like glob(), rename(), and preg_* functions, developers can create powerful scripts to automate file management tasks with precision. Happy coding!