PHP - FTP filename encoding issue

2019-03-27 22:52发布

问题:

I will be brief. My FTP function returns wrong encoding of filenames

$conn_id = ftp_connect("site.com");
ftp_login($conn_id, "login", "pass");
ftp_pasv($conn_id, true);
$buff = ftp_nlist($conn_id, "./");
print_r($buff);

->  // result
    array() {
        [0]=> "��.txt"
    }

The file name has Windows-1251 encoding.

I tried to connect to FTP via nodejs but it also returns something creepy — òð.txt.

My desktop client (WinSCP) however works fine with this.

PS: I tried to use utf8_encode - but that's also not working for me.

回答1:

If the encoding is of you could try to change it using mb_convert_encoding. The code below should output the correct value.

<?php
echo mb_convert_encoding($buff[0], "UTF-8");
//or
echo mb_convert_encoding($buff[0], "UTF-8", "windows-1251");
?>

If it doesnt work, you can try to find the right encoding using something like

<?php
foreach(mb_list_encodings() as $chr){
  echo mb_convert_encoding($buff[0], 'UTF-8', $chr)." : ".$chr."<br>"; 
} 
?>


回答2:

First you add content type on your page.

header('Content-Type: text/html; charset=utf-8');

And then try this, hope it helps

str_replace(array('%82','%94','+'),array('&#233;','&#246;',' '),urlencode($folder_name));

It's not the best way, but it works for me, if you url encode a string it changes the awkward characters into e.g. %82... You can then replace these with the HTML codes.



回答3:

Many (but not all) ftp servers supports UTF-8 pathnames encoding. You can turn this feature on by issuing 'OPTS UTF8 ON' command before ftp_nlist call.

ftp_raw('OPTS UTF8 ON');


回答4:

you can try using iconv function. Hoping it will solve your problem.



标签: php encoding ftp