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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程