Click to See Complete Forum and Search --> : PHP and Linux file names


mesh2005
04-16-2008, 07:16 PM
I have a PHP script that takes an input from the user and writes a file with the same name as the input
for example, if the user enters: this is a test a file name is created with the name this is a test.php
The problem happens when the user enters a value that contains characters not allowed in filenames on Linux distributions, how do I convert the value to make sure that it contains only allowed chars?

Thank you

NogDog
04-16-2008, 07:55 PM
While you can actually use pretty much all standard ASCII characters, many can require escaping when trying to reference them. Therefore for sanity's sake, I'd suggest only allowing letters, numbers, underscores, hyphens, and periods. You could then use a regex to convert anything else to an underscore or hyphen, e.g.:

$filename = preg_replace('/[^\w\-\.]/', '_', $user_supplied_value);

mesh2005
04-17-2008, 03:13 AM
Thank you for your reply. It seems that the problem happen when the filename contains characters of other encodings like (’), it is not the usual single quote. How can I make sure that the encoding is the right one for filenames?