PHP 检测文件系统编码/保存具有非拉丁文件名的文件
我需要使用 PHP 将非拉丁文件名的文件保存在文件系统上。
我想让这个工作跨平台。我如何知道可以使用什么编码来写入文件?我知道许多现代文件系统都是基于 UTF-8 的(这是正确的吗?),但我怀疑 Windows XP 是基于 UTF-8 的。
那么,有没有一种稳健的检测机制呢?
I need to save files with non-latin filenames on a filesytem, using PHP.
I want to make this work cross-platform. How do I know what encoding I can use to write the file? I understand many modern filesystems are UTF-8 based (is this correct?), but I doubt Windows XP is (for instance).
So, is there a robust detection mechanism?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不是您问题的答案,但如果您不需要在文件系统级别执行大量操作(例如搜索、排序...),对于 这个问题:
URLEncode()
文件名。变成
可以在任何文件系统中安全使用并且能够映射任何 UTF-8 字符。
我发现这比尝试“本地”处理主机操作系统的功能要好得多,后者肯定会很复杂且容易出错(除了操作系统差异之外,我确信各种文件系统格式 - FAT16、FAT32、NTFS 、extFS 版本 1/2/3...有自己的一套规则需要注意。)
Not an answer to your question, but if you don't need to do extensive operations on filesystem level (like searching, sorting...), there is a nice cross-platform workaround for the issue outlined in this SO question:
URLEncode()
ing file names.gets turned into
which should be safe to use in any filesystem and is able to map any UTF-8 character.
I find this much preferable to trying to "natively" deal with the host OS's capabilities, which is guaranteed to be complicated and error-prone (in addition to operating system differences, I'm sure the various filesystem formats - FAT16, FAT32, NTFS, extFS versions 1/2/3.... bring their own set of rules to be aware of.)
PHP 7.1 在 Windows 上支持 UTF-8 文件名(在更新 PHP 和 Apache 之前,我在提供名称中包含西里尔字母的文件时遇到了问题),因此,如果您可以更新 PHP,那么这是最强大且跨平台的这几天的解决方案。
我什至不需要
ini_set('mbstring.internal_encoding','UTF-8');
即可使file_get_contents
与非拉丁路径正常工作。PHP 7.1 supports UTF-8 filenames on Windows (I had a problem with serving a file with cyrillics in it's name until I've updated PHP – and Apache), so if you can just update PHP, that's the most robust and cross-platform solution these days.
I don't even need to
ini_set('mbstring.internal_encoding','UTF-8');
forfile_get_contents
to work properly with non-latin paths.