PHP: escape filename as linux does

I am having problems downloading files by users that I have to process. When I try to access them because some of them have special characters, the command used says that the file was not found or similar.

I used escapeshellcmd without sucess.

When I use the tab key in the linux console (when you started to enter the file name and you want to complete it), bash will delete the file name correctly, and if I use this escaped filename, it works.

I tried this:

preg_replace("/[^a-zA-Z0-9\-\.\s]/", "\\\\$0", $filename) 

to avoid everything except numbers, letters, and spaces ... but I found that for the file "test_1.jpg" this command converts it to "test_1.jpg" and this does not work because "_" does NOT need to be converted.

I'm afraid there might be more "allowed" characters, so my question is ... how can I "clone" the escape function "tab" in the linux bash console?

Thanks!

+3
php filenames escaping
source share
3 answers

I use this for both file names and for creating URLs from blog post headers, etc.

 // everything to lower and no spaces begin or end $path = strtolower(trim($path)); // adding - for spaces and union characters $find = array(' ', '&', '\r\n', '\n', '+',','); $path = str_replace ($find, '-', $path); //delete and replace rest of special chars $find = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/'); $repl = array('', '-', ''); $path = preg_replace ($find, $repl, $path); 
+2
source share

If you want to use the file name as a parameter to the shell command, you can use the escapeshellarg function.

+2
source share

If you access these files directly on your web server, your file names should be encoded with urlencode, not escapeshellcmd

0
source share

All Articles