简体   繁体   English

对于用户提供的文件名,正则表达式是安全的 - PHP

[英]Is a regex safe for user supplied filenames - PHP

I know the golden rule, never trust user supplied filenames. 我知道黄金法则,永远不要相信用户提供的文件名。 I want to break that rule though. 我想打破这个规则。 Is there anything unsafe about the following scheme? 以下方案有什么不安全之处吗?

   $name = $_POST['name'];
   $id = intval($_GET['id']);

   $sanitized_name = preg_replace('/[^0-9a-zA-Z]/','',$name);

   $fp = fopen("/path/to/".$id."/".$sanitized_name.".jpg",'w');

If I replace everything that is NOT 0-9 or az or AZ with '' then there's absolutely 0% change anyone can inject a '.' 如果我用''替换不是0-9或az或AZ的所有内容,那么绝对有0%的变化,任何人都可以注入'。' to create their own extension (with the combination of a NULL byte) or traverse a directory. 创建自己的扩展(使用NULL字节的组合)或遍历目录。 This seems safe. 这似乎很安全。 I just wanted to run it by SO. 我只是想通过SO运行它。

Also since the ID is forced to be an int, anything funky will simply turn into a 0. 此外,由于ID被强制为int,所以任何时髦的东西都会变成0。

If by secure you mean the user can't force upload in another folder or for another extension, yeah, this is good. 如果安全你的意思是用户不能强制上传到另一个文件夹或另一个扩展,是的,这是好的。

Addtionnaly, for making the filename "more unique", you can add a timestamp time() and / or a random number rand(0, MAX) in the filename. Addtionnaly,为了使文件名“更加独特”,您可以在文件名中添加时间戳time()和/或随机数rand(0, MAX)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM