doude5860 2019-06-09 08:59
浏览 75

如何使用php压缩另一个网站目录中的某些文件

I want to create a zip file, the content of the file was retrieved from another website. For example I have file:

http://examples.com/path/file.txt

and I want to download file.txt as a zip file. I tried with file_get_contents(); but it's not working.

$content = file_get_contents(http://examples.com/path/file.txt);
$zip = new ZipArchive;
$res = $zip->open('config.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString(file.txt, $content);
    $zip->close();
    echo 'OK';
} else {
    echo 'Failed';
}

I think it will get the content of file.txt, and create a compressed zip file, but when i open the output file it is not (incomplete sentence).

  • 写回答

1条回答 默认 最新

  • dongshou9343 2019-06-09 11:37
    关注

    I would rather use gzencode() if you need just 1 file compression :

    // dump & compress
    $file = '/tmp/image.png.gz';
    $content = file_get_contents('https://dummyimage.com/600x400/aff/bbb');
    $compr = gzencode($content, 9);
    file_put_contents($file, $compr);
    
    // download
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    

    Keep in mind that there can be various file permissions / isolation problems. For example by default Ubuntu isolates /tmp folder for a PHP process. If you want /tmp folder for a PHP process to be global - you must set PrivateTmp feature to FALSE.

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料