Home >Backend Development >PHP Tutorial >PHP detects system folder path encoding through workaround
Recently, I am writing a web-ftp platform similar to ftp through php;
It needs to be compatible with the path access of linux and window;
In the process, I found that the path encoding used by window and linux is different. For example, linux seems to be utf-8. window is gbk;
The encoding of PHP is utf-8. If there is Chinese in the path, use utf-8 encoding to access the path, and fs methods such as file_exists will be inaccessible;
Because the path does not exist, The reason is that when utf-8 parses the path encoding according to the gbk format, the Chinese must have become different characters; an error will occur because the path does not exist;
At this time, it is necessary to automatically detect the encoding of the current system,
on google After searching for a while, I couldn’t find an effective method of detecting system encoding built into PHP;
After thinking about it, I used the following solution to solve it: the current test under linux and window is correct;
```php
//Put Convert utf8 encoding to the current system encoding
protected static function _toOsCode($str, $coding = null) {
$enc = 'UTF-8';
‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ $coding = $osPathEncoding;
$osPathEncoding; , can only put one Chinese files are recycled and tested using different encodings. If the file can be read, it means the encoding is correct
protected static function _detectOsCode() {
$codingFile = '/coding-encoding-os-path.html';
$detectPath = __DIR__ .$codingFile;
$allCoding = mb_list_encodings(); |UCS-4BE |UCS-4LE|UCS-2|UCS-2BE|UCS-2LE|UTF-32|UTF-32BE|UTF-32LE|UTF-16|UTF-16BE|UTF-16LE|', '|'.$coding. '|')) {//Some encodings will be converted into illegal paths, so there is no need to detect
continue; if (@file_exists( $maybe)) {
self::_httpCode('Detect system path file (folder) name Encoding failed: One of the possible reasons is that the '.$codingFile.' file is deleted or does not have read permission, 500);
The above introduces how PHP detects the folder path encoding of the system through workarounds, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.