I\'m looking for a php function that will sanitize a string and make it ready to use for a filename. Anyone know of a handy one?
( I could write one, but I\'m worri
/
and ..
in the user provided file name can be harmful. So you should get rid of these by something like:
$fname = str_replace('..', '', $fname);
$fname = str_replace('/', '', $fname);
The following expression creates a nice, clean, and usable string:
/[^a-z0-9\._-]+/gi
Turning today's financial: billing into today-s-financial-billing
safe: replace every sequence of NOT "a-zA-Z0-9_-" to a dash; add an extension yourself.
$name = preg_replace('/[^a-zA-Z0-9_-]+/', '-', strtolower($name)).'.'.$extension;
Instead of worrying about overlooking characters - how about using a whitelist of characters you are happy to be used? For example, you could allow just good ol' a-z
, 0-9
, _
, and a single instance of a period (.
). That's obviously more limiting than most filesystems, but should keep you safe.
$fname = str_replace('/','',$fname);
Since users might use the slash to separate two words it would be better to replace with a dash instead of NULL
Making a small adjustment to Sean Vieira's solution to allow for single dots, you could use:
preg_replace("([^\w\s\d\.\-_~,;:\[\]\(\)]|[\.]{2,})", '', $file)