Home » Php » show file size when download a file by php curl

show file size when download a file by php curl

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to force download a file from server to local system by curl in php
everything is ok but the file size in which not shown when we start the download.
here is the code

    $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();

when i use this snippet
the filesize() throw an error in downloaded file and therefore corrupt the file.
i know that filesize function work with absolute path not url path, but is there any way to solve this problem?

How to&Answers:

Add the following header before the Content-Disposition header to send the filesize to the browser:

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

Source