Skip to content

Instantly share code, notes, and snippets.

@vitorbrandao
Created April 25, 2011 15:52
Show Gist options
  • Save vitorbrandao/940706 to your computer and use it in GitHub Desktop.
Save vitorbrandao/940706 to your computer and use it in GitHub Desktop.
Sanitize PHP filenames for UNIX/Linux
<?php
/**
* Helper holds a collection of static methods, useful for generic purposes
*/
class Helper
{
/**
* Returns a safe filename, for a given platform (OS), by replacing all
* dangerous characters with an underscore.
*
* @param string $dangerous_filename The source filename to be "sanitized"
* @param string $platform The target OS
*
* @return Boolean string A safe version of the input filename
*/
public static function sanitizeFileName($dangerous_filename, $platform = 'Unix')
{
if (in_array(strtolower($platform), array('unix', 'linux')) {
// our list of "dangerous characters", add/remove characters if necessary
$dangerous_characters = array(" ", '"', "'", "&", "/", "\\", "?", "#");
}
else {
// no OS matched? return the original filename then...
return $dangerous_filename;
}
// every forbidden character is replace by an underscore
return str_replace($dangerous_characters, '_', $dangerous_filename);
}
}
// usage:
$safe_filename = Helper::sanitizeFileName('#my unsaf&/file\name?"');
?>
@tqg5
Copy link

tqg5 commented May 13, 2013

Your "if" statement is missing a closing ")"

@vinvin27
Copy link

vinvin27 commented Sep 1, 2014

Nice.
But this code not protect against french accent (éàù...) ✌️

@zgr024
Copy link

zgr024 commented Mar 31, 2015

As tqg5 said, you are missing a closing ")" on line 19

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment