Snippets v2

Languages
My Snippets

Generate a Safe Filename from string Login or Register to Bookmark this snippet

Description PHP

This function strips all bad characters from a filename, that has perhaps been uploaded from a windows environment but has characters not allowed in a unix filesystem

The Code Download
  1. <?php
  2. function GenerateSafeFileName($filename) {
  3.     $filename = strtolower($filename);
  4.     $filename = str_replace("#","_",$filename);
  5.     $filename = str_replace(" ","_",$filename);
  6.     $filename = str_replace("'","",$filename);
  7.     $filename = str_replace('"',"",$filename);
  8.     $filename = str_replace("__","_",$filename);
  9.     $filename = str_replace("&","and",$filename);
  10.     $filename = str_replace("/","_",$filename);
  11.     $filename = str_replace("\","_",$filename);
  12.    $filename = str_replace("?","",$filename);
  13.    return $filename;
  14. }
  15. ?>
Credits Contact JC

Added by JC on 11th November, 2007

Comments
20th May, 2010 4:49 pm Ashley Sheridan
What is wrong with using array arguments for str_replace which could reduce that lot by 8 lines.

Also, the second-to-last replace of the backslash is breaking the function, it should be escaped as a double backslash.

Also, not sure what Unix filesystems you've been using, but you can have characters such as # and ? in the filename. It's not recommended for web-based filenames because those characters have special meaning in a URL, but it does mean that your description is a little off.
Post Comment HTML is allowed

You must be registered and logged in to post a comment.

Login here to post a comment