partho
partho

Reputation: 1084

How to download a file using php?

I want to download file from my server using php. I searched google and found a stackoverflow answer here. This answer shows that I have to write these codes for this purpose.

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) .     "\""); 
readfile($file_url); 

But I am able to do this with merely these two lines:

header("content-disposition:attachment; filename=uploads1/EFL1.5_Setup.exe");
readfile("uploads1/EFL1.5_Setup.exe");

So why I should write a few more lines like codes above?

Upvotes: 2

Views: 8255

Answers (2)

luke
luke

Reputation: 224

here is the code to download a file with the info how much percent is downloaded:

<?php
$ch = curl_init();
$downloadFile = fopen( 'file name here', 'w' );
curl_setopt($ch, CURLOPT_URL, "file link here");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 65536);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'downloadProgress'); 
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt( $ch, CURLOPT_FILE, $downloadFile );
curl_exec($ch);
curl_close($ch);

function downloadProgress ($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) {

    if($download_size!=0){
        $percen= (($downloaded_size/$download_size)*100);
        echo $percen."<br>";
    }
}
?>

Upvotes: 2

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

header('Content-Type: application/octet-stream');

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

header("Content-Transfer-Encoding: Binary"); 

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).

Reference:

Do I need Content-Type: application/octet-stream for file download?

Upvotes: 2

Related Questions