Get Safe File Name

This function come up with a function that does a good job of sanitizing certain strings so that they are safe to use in the URL (like a post slug) and also safe to use as file names. For example, when someone uploads a file I want to make sure that I remove all dangerous characters from the name.

 function filename_safe($filename) {
     $temp = $filename;
     // Lower case
     $temp = strtolower($temp);
     // Replace spaces with a '_'
     $temp = str_replace(" ", "_", $temp);
     // Loop through string
     $result = '';
     for ($i=0; $i<strlen($temp); $i++) {
         if (preg_match('([0-9]|[a-z]|_)', $temp[$i])) {
             $result = $result . $temp[$i];
     // Return filename
     return $result;

Let me know if you have any queries in using the functions.

Sudhir Tiwari

I'm technical executive with a 6 years track record of delivering complex, high value projects through development, programming , and product management. I'm solution expert in Magento, WordPress, Prestashop, X-cart, Cakephp, CodeIgniter , NetSuite.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>