PHP:像 Linux 一样转义文件名
我在处理用户上传的文件名时遇到问题,我必须处理这些文件名。当我尝试访问它们时,因为其中一些具有特殊字符,所以使用的命令表示找不到文件或类似文件。
我使用 escapeshellcmd 但没有成功。
当我在 Linux 控制台中使用“tab”键时(当您开始输入文件名并且希望它完成时),bash 会正确转义文件名,如果我完全使用“转义”文件名,它就会起作用。
我已经尝试过:
preg_replace("/[^a-zA-Z0-9\-\.\s]/", "\\\\$0", $filename)
转义除数字、字母、- 和空格之外的所有内容...但我发现对于文件“test_1.jpg”,此命令将其转换为“test_1.jpg”,并且它不起作用,因为“_”不需要转换。
我担心可能会有更多“允许”的字符,所以我的问题是......我如何“克隆”linux控制台bash中“tab”键的转义功能?
I'm having troubles with filenames upload by users which I have to process. When I try to access them, because some of them have special characters, the command used says the file is not found or similar.
I've used escapeshellcmd with no sucess.
When I use the "tab" key in linux console (when you have started to type the filename and you want it to complete), the bash escape the filename correctly, and if I use exactly that "escaped" filename, it works.
I've tried this:
preg_replace("/[^a-zA-Z0-9\-\.\s]/", "\\\\$0", $filename)
to escape everything except numbers, letters, - and spaces ... but I found that for file "test_1.jpg", this command converts it into "test_1.jpg", and it does not work, since "_" does NOT need to be converted.
I'm afraid there could be more "allowed" characters, so my question is ... how can i "clone" the escape function of "tab" key in linux console bash?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你想使用文件名作为 shell 命令参数,你可以使用函数 escapeshellarg。
If you want to use the file name as a shell command parameter you can use the function escapeshellarg.
我将其用于文件名以及根据博客文章标题等创建 URL。
I use this for both file names and for making URLs out of blog post titles and the like.
如果您直接在 Web 服务器上访问这些文件,则文件名需要使用 urlencode 进行 url 编码,而不是 escapeshellcmd
If you are accessing these files directly on your web server, your files names need to be url encoded with urlencode, not escapeshellcmd
这是我整理的功能,希望对
大家有帮助,可以通过添加 | 来添加更多 功能。与另一个转义字符
this is the function I put together, hope it helps
you can all add more by adding | with another escaped character