Categories
PHP

Renaming and Sanitizing Uploaded File Name

In this tutorial, you’ll create functions to automatically rename the uploaded file name, generate a unique file name based on the Unix timestamp, and remove special characters to sanitize the file name.

Sanitizing File Name

The sanitizeFileName() user-defined function filters the file name by removing special characters and replacing the dots hyphens and underscores with a hyphen:

<?php
 function sanitizeFileName($fileName) {
  $arr = ['?','[',']','/','\\','=','<','>',':',';',',', "'",'"','&','$','#','*','(',')','|','~','`','!','{','}','%','+','’','«','»','”','“'];
  $info = pathinfo($fileName);
  $name = $info['filename'];
  $ext  = $info['extension'];
  
  $name = str_replace( $arr, '', $name );
  $name = preg_replace( '/[\. _-]+/', '-', $name );
  $name = trim( $name, '-' );
  
  return "$name.$ext"; 
 }
  1. The str_replace function removes the special characters
  2. The preg_replace replaces the space(s), hyphen(s), and underscore(s) to a hyphen.
  3. The trim function strips the hyphen character from the beginning and end of the file name.

Automatically Renaming Files if Already Exist

<?php
 if ( file_exists('uploads/sample.jpg') )
   echo 'File exists';
 else
  echo 'File not exists';

When you move an uploaded file with move_uploaded_file() function to a new location, if a file with the same name already exists in the destination folder it will be overwritten silently.

To avoid this situation, always check that the file you’re trying to move doesn’t already exist in the destination directory. The file_exists() function checks whether a file or directory exists.

Example: Creating a function to rename the file if already exists in the destination

This function renames a file by appending a number to its name suffix if the file already exists in the destination directory. For example, if readme.txt, readme1.txt, and readme2.txt files already exist in the destination folder then the renameFileIfExists() function returns readme3.txt for the file readme.txt file:

<?php 
 function renameFileIfExists($name, $dir) {
  $file = $dir.DIRECTORY_SEPARATOR.$name;
  $info = pathinfo($file);
  $i = 0;
  while ( file_exists($file) ) {
   $i++;
   $file = $info['dirname'] .DIRECTORY_SEPARATOR
          .$info['filename'].$i.'.'
          .$info['extension'];  
  }
  return pathinfo($file, PATHINFO_BASENAME);
 }

 $uploadDir = 'uploads';
 $fileName = 'readme.txt'; //$_FILES['uploads']['name'];

 $newName = renameFileIfExists($fileName, $uploadDir);
 echo $newName;
 // Prints: readme3.txt
 // as readme.txt, readme1.txt, and readme2.txt
 // files are already exist in my uploads dir

Generating Unique File Name

<?php
 echo microtime(true).'.png';
 // Prints: 1666419599.9488.png

 echo time() . '.png';
 // Prints: 1666419599.png

If you don’t want to use the file name sent by the user form, you can generate a unique file name using PHP time() or microtime() functions:

<?php 
 function generateFileName($oldName, $uploadDir) {
  $ext = pathinfo($oldName, PATHINFO_EXTENSION);

  $newFileName = time() . '.' .$ext;
  //$newFileName = microtime() . '.' .$ext;

  $file = $uploadDir.DIRECTORY_SEPARATOR.$newFileName;
  $info = pathinfo($file);
  $i = 0;
  while ( file_exists($file) ) {
   $i++;
   $file = $info['dirname'] .DIRECTORY_SEPARATOR
          .$info['filename'].$i.'.'
          .$info['extension'];  
  }
  return pathinfo($file, PATHINFO_BASENAME);
 }

 $uploadDir = 'uploads';
 $fileName = 'readme.txt'; //$_FILES['uploads']['name'];

 $newName = generateFileName($fileName, $uploadDir);
 echo $newName;
// Prints: 1666420453.txt

Processing Forms in PHP: