16

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

 2 years ago
source link: https://www.codexworld.com/how-to/clean-up-filename-string-to-make-url-and-filename-safe-using-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Home  »  How To Guides  »  PHP   »   How to Clean up Filename String to make URL and Filename Safe using PHP

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_name, PATHINFO_EXTENSION);
    $file_name_str = pathinfo($file_name, PATHINFO_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

Cancel

Comment*

Your Name*

Your Email*

Your Website


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK