How to Clean up Filename String to make URL and Filename Safe using PHP

The special characters should be removed from the filename and URL to make it safe. When a web application creates a file and dynamic URL, it is convenient to use only characters and numbers to avoid portability issues. You can sanitize the string before assigning it for filename or URL slug.

Make sure to filter all the unwanted characters from the filename to make the URL and filename safe. PHP preg_replace() function is very useful to clean up filename string in PHP. This example code snippet allows to remove unsafe characters from a string and make filename URL safe using PHP.

The cleanFileName() is a custom PHP function that sanitizes the given filename string and returns a clean filename.

<?php 
function cleanFileName($file_name){
    
$file_ext pathinfo($file_namePATHINFO_EXTENSION);
    
$file_name_str pathinfo($file_namePATHINFO_FILENAME);
    
    
// Replaces all spaces with hyphens.
    
$file_name_str str_replace(' ''-'$file_name_str);
    
// Removes special chars.
    
$file_name_str preg_replace('/[^A-Za-z0-9\-\_]/'''$file_name_str);
    
// Replaces multiple hyphens with single one.
    
$file_name_str preg_replace('/-+/''-'$file_name_str);
    
    
$clean_file_name $file_name_str.'.'.$file_ext;
    
    return 
$clean_file_name;
}

Leave a reply

keyboard_double_arrow_up