【问题标题】:show file size when download a file by php curl通过 php curl 下载文件时显示文件大小
【发布时间】:2020-05-30 13:06:27
【问题描述】:

我想通过 php 中的 curl 强制将文件从服务器下载到本地系统 一切都很好,但是我们开始下载时没有显示文件大小。 这是代码

    $file_url ='http://example.com/dl/dlfile.zip';

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file_url)); 
    // header('Content-Transfer-Encoding: chunked'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    $stream = fopen('php://output', 'w');
    $ch = curl_init($file_url);

    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_url));

    curl_setopt($ch, CURLOPT_READFUNCTION, function($ch, $fd, $length) use ($stream) {
        return fwrite($stream, fread($fd, $length));
    });
    curl_exec($ch);
    curl_close($ch);
    exit();

当我使用这个 sn-p filesize() 会在下载的文件中引发错误,从而损坏文件。 我知道文件大小函数使用绝对路径而不是 url 路径,但是有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: php curl download


    【解决方案1】:

    Content-Disposition 标头之前添加以下标头以将文件大小发送到浏览器:

    header("Content-Length: ".filesize($file_url));
    

    Source

    【讨论】:

    • 有什么解决办法吗?
    • 我确信有,但是,它很难测试,因为它有点依赖上下文。
    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    相关资源
    最近更新 更多