Securely Renaming a Massive Amount of Files with PHP – The Non-Destructive Route

A recent project scope included renaming (literally) tens of thousands of documents for security purposes – it’s not too secure having files name “November-2011-Finances.doc” hosted online.

This tutorial will explain how to use PHP locally (without a web server like XXAMP, MAMP, or WAMP). Using one of these 3 services is fine, but we decided to go the system route!

I will break this tutorial down into multiple parts:

Part One: Reading a folder structure recursively.
Part Two: Renaming the files (uniquely) and storing new and old file paths.
Part Three: Copy the files into a sequenced folder system. ( Coming Soon )

Note: I’ll save you the hassle I had with the “guess and check” method of installing PHP locally. Here are some great tutorials on how to install PHP locally on Mac and Windows.

Part One: Reading a folder structure recursively.

Note: I am using a class for this, simply because i was having issues with functions not completing before other commands run.

First, we need to be able to call our script.php file. Use your favourite text editor, and create your PHP file with a simple script like:

 

Next, open your command line on your computer (Terminal on Mac OSX, Command Prompt on Windows) and put in the following line:

 php C:\path\to\your\script.php

In your command line, you should see “Hello World”. This is a good sign that you are calling your file correctly.

The Command

This is the final command we will be using in command line:

php E:\your-folder\script.php -c E:\files-to-copy -n E:\folder-for-copied-files -l E:\your\logfile

This is running the PHP file located at E:\your-folder\script.php and accepting the following parameters:

• -c : current directory (the files to copy)
• -n : new file directory (where you want the files to go)
• -l : the directory and name of your log file ( we will write a CSV spreadsheet file with new and old names)

The second task is accepting the parameters we pass through command line:

 

The second task is setting up a loop to go through all files, and dig into subfolders as you come across them. Here is a for loop that we will use to recursively read through the subfolders.

 

That’s it! So we initiate our script’s class, after passing the directory we want to read’s path. The read_directories() function will start in the folder we pass it, display all files it finds, and when it comes accross a folder, it will recursively pass the folder back through the read_directories() function. You can have unlimited folder nesting, and this function will find all files inside the parent directory!

In part 2 of this tutorial, we will store the files we come across, and create new unique names for them. I hope you have enjoyed so far!