Comparing to ColdFusion, which automatically renames a file upon upload in case the file already exists, php unfortunately does not provide any function doing so. This tutorial shows how to create a very simple function that adds a randomly generated prefix to the file name.

We are going to slightly modify the upload function that I wrote in my previous tutorial see: Multiple Files Upload.

Below is a function that generates the random prefix:

function generate_file_prefix ($num_of_digits) {
if($length>0) {
while(strlen($prefix)<$num_of_digits) {
$prefix.=$numbers[mt_rand(0, strlen($numbers)-1)];
return $prefix;

All we have to do now is modify the bit of file upload, so when the file is detected rather than using unlink() to removes it, we may call above function to rename the file by adding an additional prefix and upload in normal manner.

if (file_exists($filePath)) {
$currentFile = simpleRandNum(3).$currentFile;
$filePath = $uploadDir . $currentFile;