Fix a string in PHP for use in Unix Filenames

Language: PHP

Problem: You are trying to use a string as or in a UNIX filename (for instance, passing a filename to a command within the exec() function) and addslashes() falls short because it doesn’t include spaces or ampersands.
Solution: It’s rough but it works fine.  Run your strings through this function first, and don’t use surrounding quotation marks (no need).  If you’ve got a better one or have questions, leave a comment 🙂

[sourcecode language=’php’]
function makeUnixFilename($string)
{
return str_replace(“&”,’\&’,str_replace(” “,’\ ‘,addslashes($string)));
}
[/sourcecode]

Leave a Reply

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