Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

hebrew - PHP ZipArchive non-English filenames return funky filenames within archive

This code works properly to make the ZIP file with the wanted files, except the filenames in the archive, which are not in English (in this case they are Hebrew), have weird characters instead of the proper hebrew letters.

<?php
$filesfordown = $_POST['GEMin'];
    if(empty($filesfordown)) 
    {
        echo "No files were seleceted for download.";
    } 
    else 
    {
$zip_name = "RMW." . time() . ".zip";
$zip = new ZipArchive;
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($filesfordown as $filefordown) {
  $zip->addFile($filefordown);
}
$zip->close(); }

header('Content-Type: application/zip');
header("Content-disposition: attachment; filename='$zip_name'");
header('Content-Length: ' . filesize($zip_name));
readfile($zip_name);

ob_flush;
?>

I did some searching around, it seems that iconv, setlocalte, or mb_convert_encoding might help, but whatever I tried didn't work.

Any ideas?

P.S. As a side question, is there a way to not keep directory structure in the zip?

ETA: An example of the $_post may be www.domain.com/path/????_01.mp3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yay! Fixed!

First the code, then an explanation:

<?php 
setlocale(LC_ALL, 'he_IL.UTF-8');
$filesfordown = $_POST['GEMin'];
    if(empty($filesfordown)) 
    {
        echo "?? ?????.. ??? ???";
    } 
    else 
    {
$zip_name = "RMW" . time() . ".zip";
$zip = new ZipArchive;
$zip->open($zip_name, ZipArchive::CREATE);
echo "???? ?? ??????...";
foreach ($filesfordown as $filefordown) {
  $zip->addFile($filefordown, iconv("UTF-8","CP862",basename($filefordown)));
}
$zip->close(); 

3 things needed to be changed.

  1. Verify that the actual php file is UTF-8.
  2. setlocale() needs to include the .UTF-8 at the end.
  3. ZipArchive does not handle UTF-8 correctly. Must use CP. Hebrew was CP862. Therefore, use extra option $localname for addFile, and its basically iconv("UTF-8","CODE_PAGE_REF",$localname)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...