Write a PHP code to download file.
This PHP script will allow you to download the PDF file directly without opening it. But if want to add more file support you can do it by adding another pice of code. Place your code where is written “add more file et here”. You can copy the above case but you have to change the IMEI type for file.
First of all create a PHP script called “download.php” and copy the code given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php // place this code inside a php file and call it f.e. "download.php" $path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure $fullPath = $path.$_GET['download_file']; if ($fd = fopen ($fullPath, "r")) { $fsize = filesize($fullPath); $path_parts = pathinfo($fullPath); $ext = strtolower($path_parts["extension"]); switch ($ext) { case "pdf": header("Content-type: application/pdf"); // add here more headers for diff. extensions header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download break; //add more file ext here default; header("Content-type: application/octet-stream"); header("Content-Disposition: filename=\"".$path_parts["basename"]."\""); } header("Content-length: $fsize"); header("Cache-control: private"); //use this to open files directly while(!feof($fd)) { $buffer = fread($fd, 2048); echo $buffer; } } fclose ($fd); exit; // example: place this kind of link into the document where the file download is offered: // <a href="download.php?download_file=some_file.pdf">Download here</a> ?> |
Now, If you want to use this code follow these instruction. Add this pice of code where you want to place your downed link. Don’t forget to change “some_file.pdf” with your file name.
1 2 3 | <a href="download.php?download_file=some_file.pdf">Download here</a> |
If you have any question or suggestions, please drop a comment below.