How to make a download link in PHP?

I can upload a file to the database using sql, but how can I make a download link? for example, when you download something on the Internet, a window appears informing you whether you want to open it using the program or save it. how can i do this in php? can you give me the codes for this? I'm still a noob.

+4
source share
2 answers

Put this code on the page (together with the PHP code to get information from the database and put it in variables for name / size / data, then a link to this page.

<?php header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $name_of_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: ' . $size_of_file); echo $file_data; ?> 

Not all the headers listed above are strictly necessary - in fact, for the load to work correctly, only the Content-Type header is really needed. The Content-Disposition header is good for inclusion so you can specify the correct file name; others simply help the browser handle the download better and may be omitted if you wish.

+10
source

Some changes to this code to make it work in my case. - For MP3

You can call this by calling this filedownload.php file - put it on your server.

Call it from a file, for example: from the WordPress Custom field in this example

 <a href="<?php bloginfo('url'); ?>/filedownload.php?download=<?php echo get_post_meta($post->ID, 'mymp3_value', true) ?>">MP3</a> 

Very easy to do.

 <?php $name_of_file = $_GET["download"]; header('Content-Description: File Transfer'); // We'll be outputting a MP3 header('Content-type: application/mp3'); // It will be called file.mp3 header('Content-Disposition: attachment; filename=' .$name_of_file); header('Content-Length: '.filesize($name_of_file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); // The MP3 source is in somefile.pdf //readfile("somefile.mp3"); readfile_chunked($name_of_file); function readfile_chunked($filename) { $chunksize = 1*(1024*1024); // how many bytes per chunk $buffer = ''; $handle = fopen($filename, 'rb'); if ($handle === false) { return false; } while (!feof($handle)) { $buffer = fread($handle, $chunksize); print $buffer; } return fclose($handle); } ?> 
+1
source

All Articles