Reputation: 89
How do I make php force download a file. I have a file named song1, which is a song, in the file songs. so from the page I am at it is song/song1. How do I make php download the file as soon as the php is ran?
Upvotes: 0
Views: 37
Reputation: 2358
Try below code
$file='song1.mp3';
if (file_exists('song/'.$file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('song/'.$file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize('song/'.$file));
ob_clean();
flush();
readfile('song/'.$file);
}
It will directly download file.
Upvotes: 0
Reputation: 3923
You have to send out some HTTP headers:
header('Content-disposition:attachment; filename=song.mp3;');
Then you have to pull the song data with for example file_get_contents()
. And finally use a die()
or exit()
to avoid adding extra data.
Side note: The above code will not work if you've already sent out HTTP headers (wrote out some whitespace characters, etc), so put it directly after <?php
if you can.
Upvotes: 1