0

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?

1 Answers1

0

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

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

Source

dearsina
  • 4,774
  • 2
  • 28
  • 34