duanjia4097 2012-09-28 11:58
浏览 127
已采纳

PHP readfile()返回损坏的数据

In my function I am saving an image decoded from a base64 string:

function saveImage(){
    //magic...
    define('UPLOAD_DIR', '../webroot/img/');
    $base64string = str_replace('data:image/png;base64,', '', $base64string);
    $base64string = str_replace(' ', '+', $base64string);
    $data = base64_decode($base64string);
    $id = uniqid();
    $file = UPLOAD_DIR.$id.'.png';
    $success = file_put_contents($file, $data);
}

The above function works properly and the images are saved and not corrupted in the specified folder.

In the next function I am now trying to force download the image to a user:

function getChart($uniqid= null){
    if($uniqid){
        $this->layout = null;
        header("Content-type: image/png");
        header("Content-Disposition:attachment;filename='".$uniqid.".png'");
        readfile('../webroot/img/'.$uniqid.'.png');
        exit;
    } else exit;
}

Image downloaded from the server is corrupted and cant be displayed. After opening the downloaded file in a text editor I noticed that a new line character is added at the very top. After deleting the character and saving the file it opens properly and is being displayed properly.

How can I fix this?

  • 写回答

6条回答 默认 最新

  • drymoeuka282427675 2012-09-28 12:07
    关注

    What you describe can have multiple issues that are hidden until you actually open the downloaded file.

    Instead make your code more robust and check pre-conditions, here if headers have been send already and to clean any possible existing output buffer and give error if that is not possible:

    function getChart ($uniqid = null) {
    
        if (!$uniqid) exit;
    
        $this->layout = null;
    
        if (headers_sent()) throw new Exception('Headers sent.');
        while (ob_get_level() && ob_end_clean());
        if (ob_get_level()) throw new Exception('Buffering is still active.');
    
        header("Content-type: image/png");
        header("Content-Disposition:attachment;filename='".$uniqid.".png'");
        readfile('../webroot/img/'.$uniqid.'.png');
    
        exit;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿