php通過變通方法檢測系統的檔案夾路徑編碼,

來源:互聯網
上載者:User

php通過變通方法檢測系統的檔案夾路徑編碼,
最近在通過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);
        }         
    }


```

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.