最近在通过php来写一个类似ftp的的web-ftp平台;
需要兼容linux和window的路径访问;
过程中发现window与linux使用的路径编码是不一样的,比如linux好像是utf-8,window却是gbk;
php的编码是utf-8,如果路径中有中文,统一使用utf-8编码来访问路径,就会出现像file_exists这类fs方法出现无法访问情况;
因为路径不存在,原因就是utf-8按照gbk的格式来解析路径编码时,肯定是中文变成不的字符了;就出现路径不存在而出错;
这时就需要自动的检测当前系统的编码,
在google上找了一下,没找到有效的php内置的检测系统编码的方法;
想了一下,我使用以下方案来解决:目前在linux和window下测试是正确的;
```php
//把utf8编码转成当前系统编码
protected static function _tooscode($str, $coding = null) {
$enc = 'utf-8';
if (empty($coding)) {
$coding = self::$ospathencoding;
}
$str = mb_convert_encoding($str, $coding, $enc);
return $str;
}
//检测系统编码
//目前没有找到合适的方法,只能是放一个中文文件,再循环使用不同的编码检测,能读到文件就说明编码是正确的
protected static function _detectoscode() {
$codingfile = '/编码-encoding-os-path.html';
$detectpath = __dir__ .$codingfile;
$allcoding = mb_list_encodings();
foreach ($allcoding as $coding) {
if (false !== stripos('|byte2be|byte2le|byte4be|byte4le|ucs-4|ucs-4be|ucs-4le|ucs-2|ucs-2be|ucs-2le|utf-32|utf-32be|utf-32le|utf-16|utf-16be|utf-16le|', '|'.$coding.'|')) {//某些编码会转成非法路径,所以,不需要检测
continue;
}
$maybe = self::_tooscode($detectpath, $coding);
if (@file_exists($maybe)) {
self::$ospathencoding = $coding;
break;
}
}
if (empty(self::$ospathencoding)) {
self::_httpcode('检测系统路径文件(夹)名称的编码失败:可能原因之一是'.$codingfile.'文件被删除或没有读取权限', 500);
}
}
```
以上就介绍了php通过变通方法检测系统的文件夹路径编码,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。