Heim  >  Artikel  >  Backend-Entwicklung  >  php通过变通方法检测系统的文件夹路径编码

php通过变通方法检测系统的文件夹路径编码

WBOY
WBOYOriginal
2016-08-08 09:23:01937Durchsuche

最近在通过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教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php selfNächster Artikel:Yii 添加自己的搜索条件