: This article describes how php detects the folder path encoding of the system by using work ing methods. For more information about PHP tutorials, see. I recently wrote a ftp-like web-ftp platform through php;
Must be compatible with the path access of linux and Windows;
During the process, we found that the path encoding used by Windows is different from that used by linux. for example, linux seems to be UTF-8, while windows is gbk;
Php uses UTF-8 encoding. if the path contains Chinese characters and uses UTF-8 encoding to access the path, the fs methods like file_exists may be inaccessible;
Because the path does not exist, the reason is that when UTF-8 is used to parse the path encoding in gbk format, it must be a Chinese character that cannot be changed; then the path does not exist and an error occurs;
In this case, you need to automatically detect the encoding of the current system,
I found it on google and did not find an effective php built-in detection system encoding method;
After thinking about it, I used the following solution to solve the problem: Currently the test in linux and Windows is correct;
"Php
// Convert utf8 encoding to the current system encoding
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;
}
// Detection system code
// Currently, no proper method is found. Only one Chinese file can be stored, and different encoding methods can be used for recycling. if you can read the file, the encoding is correct.
Protected static function _ detectOsCode (){
$ CodingFile = '/ -encoding-ospath.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 | ', '| '. $ coding. '|') {// Some encodings are converted into invalid paths. therefore, no detection is required.
Continue;
}
$ Maybe = self: _ toOsCode ($ detectPath, $ coding );
If (@ file_exists ($ maybe )){
Self: $ osPathEncoding = $ coding;
Break;
}
}
If (empty (self: $ osPathEncoding )){
Self: _ httpCode ('Encoding of the system Path File (folder) name failed: one of the possible reasons is '. $ codingFile. 'The file is deleted or has no read authorization', 500 );
}
}
"
The above describes how php detects the folder path encoding of the system by using work ing methods, including content, and hopes to help friends who are interested in PHP tutorials.