Recently in PHP to write an FTP-like WEB-FTP platform;
Requires path access compatible with Linux and Windows;
The process found that window and Linux use the path encoding is not the same, such as Linux seems to be Utf-8,window but GBK;
PHP encoding is utf-8, if the path has Chinese, unified use UTF-8 encoding to access the path, there will be such as file_exists such a method of FS can not access the situation;
Because the path does not exist, the reason is that utf-8 in accordance with the format of GBK to parse the path encoding, it must be Chinese into a character, the occurrence of a path does not exist and error;
This will require automatic detection of the current system's code,
Found a bit on Google, did not find a valid PHP built-in detection system coding method;
Thinking about it, I use the following scenario to solve: currently under the Linux and window testing is correct;
"' PHP
Convert UTF8 encoding to current system code
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 Coding
At present, there is no suitable method, can only be placed in a Chinese file, and then cycle the use of different encoding detection, can read the file on the code is correct
protected static function _detectoscode () {
$codingFile = '/coded-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. ' | ')) {//Some encoding is turned into an illegal path, so no detection is required
Continue
}
$maybe = Self::_tooscode ($detectPath, $coding);
if (@file_exists ($maybe)) {
Self:: $osPathEncoding = $coding;
Break
}
}
if (Empty (self:: $osPathEncoding)) {
Self::_httpcode (' Detection system path file (folder) name encoding failed: One of the possible reasons is '. $codingFile. ' File is deleted or no Read permission ', 500);
}
}
```
PHP detects the system's folder path encoding by using the workaround method