PHP 转义用户输入的文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4289905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP escape user input for filename
提问by munchybunch
I have a form where users can upload files, and I'd like to name the file something along the lines of [id]_[lastname]_[firstname].pdf
. The name is entered by the user, and I'm afraid of them entering something with a slash in it. Otherwise, something like $path = $dir.$filename
could result in $path = 'uploads/2_smith_john/hahaimajerk.pdf'
if the firstname is john/hahaimajerk
.
我有一个用户可以上传文件的表单,我想将文件命名为[id]_[lastname]_[firstname].pdf
. 该名称由用户输入,我担心他们输入带有斜杠的内容。否则,像$path = $dir.$filename
可能会导致$path = 'uploads/2_smith_john/hahaimajerk.pdf'
如果名字是john/hahaimajerk
。
I don't really want to force users to restrict their names to anything; I don't mind changing their names a little in the file name as long as I can tell the original name. What characters do I need to escape, or is there some other way to do this? Or...do I just use mysql_real_escape_string
?
我真的不想强迫用户将他们的名字限制在任何东西上;只要我能说出原始名称,我不介意在文件名中稍微更改它们的名称。我需要转义哪些字符,或者有其他方法可以做到这一点?或者...我只是使用mysql_real_escape_string
?
采纳答案by netcoder
mysql_real_escape_string
won't escape slashes. Even escapeshellarg
won't do it. You will have to use str_replace
:
mysql_real_escape_string
不会逃避斜线。甚至escapeshellarg
不会做。你将不得不使用str_replace
:
$path = str_replace('/', '_', $path);
回答by Tommy Lacroix
I usually use regular expressions for this. And instead of removing certain specific characters (like slashes, dots, etc), I prefer to only allow certain characters (like alphanumeric)
我通常为此使用正则表达式。而不是删除某些特定字符(如斜杠、点等),我更喜欢只允许某些字符(如字母数字)
For instance, this will replace any character that is not a letter, a number, a dash or an underscore by an underscore:
例如,这将用下划线替换任何不是字母、数字、破折号或下划线的字符:
$escaped = preg_replace('/[^A-Za-z0-9_\-]/', '_', $raw);
The backslash before the dash is to escape the dash in the regular expression, as dashes are otherwise used to specify character ranges (such as A-Z).
破折号前的反斜杠用于在正则表达式中对破折号进行转义,因为破折号否则用于指定字符范围(例如 AZ)。
回答by Niet the Dark Absol
The only "unsafe" character in a filename is /
- so you can easily avoid problems by using str_replace("/","",$filename)
文件名中唯一的“不安全”字符是/
- 因此您可以通过使用轻松避免问题str_replace("/","",$filename)
回答by memical
escapeshellcmd might help too.
escapeshellcmd 也可能有帮助。
http://php.net/manual/en/function.escapeshellcmd.php
http://php.net/manual/en/function.escapeshellcmd.php
echo escapeshellcmd("\/()_") -> will display \/\(\)_