Saving a Base64 string to disk as a binary using PHP

前端 未结 8 1482
无人及你
无人及你 2020-12-24 15:01

As a \"look under the covers\" tutorial for myself I am building a PHP script to gather emails from a POP3 mailbox. While attempting to make use of binary attachments I am

相关标签:
8条回答
  • 2020-12-24 15:41

    If you have a lot of data to write out that needs to be decoded before writing I would suggest using stream filters so decode the data as you write it...

    $fh = fopen('where_you_are_writing', 'wb');
    stream_filter_append($fh, 'convert.base64-decode');
    
    // Do a lot of writing here. It will be automatically decoded from base64.
    
    fclose($h);
    
    0 讨论(0)
  • 2020-12-24 15:44

    While reinventing the wheel has some entertainment and educational value, I would try to resist the temptation: Mailparse, Mail_mimeDecode

    0 讨论(0)
  • For big base64 strings from a DB you need use load()

    $imgdata = $FromDB['BASE64']->load();
    $imgdata =  base64_decode($imgdata);
    file_put_contents($fileName, $imgdata);
    
    0 讨论(0)
  • 2020-12-24 15:55

    Chop off first and last line, base64decode and save under given filename.

    done.

    0 讨论(0)
  • 2020-12-24 15:57

    Pass the data to base64_decode() to get the binary data, write it out to a file with file_put_contents()

    0 讨论(0)
  • 2020-12-24 16:02
    function base64_decode_file($data)
    {
        if(preg_match('/^data\:([a-zA-Z]+\/[a-zA-Z]+);base64\,([a-zA-Z0-9\+\/]+\=*)$/', $data, $matches)) {
            return [
                    'mime' => $matches[1],
                    'data' => base64_decode($matches[2]),
            ];
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题