mesh2005 Posted April 17, 2008 Share Posted April 17, 2008 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 Quote Link to comment Share on other sites More sharing options...
jonsjava Posted April 17, 2008 Share Posted April 17, 2008 <?php $comment = "this is a test"; $clean = str_replace(" ", "" $comment); ?> Quote Link to comment Share on other sites More sharing options...
marcus Posted April 17, 2008 Share Posted April 17, 2008 characters, as in alphanumeric? you can do a check like: <?php $string = "this is text"; if(ctype_alnum($string)){ echo "Alphanumeric"; }else { echo "Not alphanumeric, doing a check..."; $n_string = str_replace(" ",NULL, $string); if(ctype_alnum($n_string)){ echo "<br><br>Replacing spaces caused the string to be alphanumeric"; }else { echo "<br><br>Replacing spaces caused the string to still be non-alphanumeric!"; } } ?> Quote Link to comment Share on other sites More sharing options...
mesh2005 Posted April 17, 2008 Author Share Posted April 17, 2008 Thanks guys for your replies. I wanna allow other symbols too like +/- and all possible symbols that won't cause a problem. I usually get errors when the filename is encoded in way that is not understood by Linux, for example the character (’), this character appears as unknown code in the filename, any help? Quote Link to comment Share on other sites More sharing options...
Wuhtzu Posted April 17, 2008 Share Posted April 17, 2008 Use regular expression: <?php $user_input = "this is a test"; if(preg_match("/[a-z0-9 \+_\.-]?/", $user_input)) { $file_name = $user_input . ".php"; } else { echo "Invalid characters in filename"; } ?> This will take the $user_input and make sure it only consist of a-z, 0-9, '+', '.', '-' and '_' and has a minimum length of 1. Quote Link to comment Share on other sites More sharing options...
mesh2005 Posted April 18, 2008 Author Share Posted April 18, 2008 Thanks guys. I found a very useful regex to strip out all non-ASCII chars and this saved the day. Here is it in case anyone needs it: $string = preg_replace('/[^(\x20-\x7F)]*/','', $string); Quote Link to comment Share on other sites More sharing options...
discomatt Posted April 19, 2008 Share Posted April 19, 2008 Not all ascii characters are allowed in a filename... '/' in particular could cause some serious issues Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.