douxing8939 2013-10-22 06:30
浏览 47
已采纳

php解码base 64非常大的文件,不是字符串

i have a system that saves files to the server harddrive in base 64 encoded after stripping them from email files.

i would like to change the file to thier original format again, how can i do that in php?

this is how i tried to save the files but that does not seem to create a valid files:

$start = $part['starting-pos-body'];
$end = $part['ending-pos-body'];
$len = $end-$start;
$written = 0;
$write = 2028;
$body = '';
while ($start <= $end) {
 fseek($this->stream, $start, SEEK_SET);
 $my = fread($this->stream, $write);
 fwrite($temp_fp, base64_decode($my));
 $start += $write;
}
fclose($temp_fp);
  • 写回答

3条回答 默认 最新

  • dongzi5062 2013-10-22 07:44
    关注

    @traylz makes the point clear for why it may fail when it shouldn't. However, base64_decode() may fail for large images even. I have worked with 6 to 7 MB files fine, I haven't gone over this size, so for me it should be as simple as:

    $dir = dirname(__FILE__);
    // get the base64 encoded file and decode it
    $o_en = file_get_contents($dir . '/base64.txt');
    $d = base64_decode($o_en);
    
    // put decoded string into tmp file
    file_put_contents($dir . '/base64_d', $d);
    
    // get mime type (note: mime_content_type() is deprecated in favour
    // for fileinfo functions)
    $mime = str_replace('image/', '.', mime_content_type($dir . '/base64_d'));
    rename($dir . '/base64_d', $dir . '/base64_d' . $mime);
    

    If the following fails try adding chunk_split() function to decode operation:

    $d = base64_decode(chunk_split($o_en));
    

    So what am I sayaing...forget the loop unless there is a need for it...keep the orignal file extension if you don't trust php's mime detection. use chunk_split() on base64_decode() operation if working on large files.

    NOTE: all theory so untested

    EDIT: for large files that mostly likely will freeze file_get_contents(), read in what you need, output to file so little RAM is used:

    $chunkSize = 1024;
    $src = fopen('base64.txt', 'rb');
    $dst = fopen('binary.mime', 'wb');
    while (!feof($src)) {
        fwrite($dst, base64_decode(fread($src, $chunkSize)));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。