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

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条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看