Download File Using Javascript And PHP
Download File Using Javascript And PHP
There are different ways to download a file. Easiest method is to use simple HTML like the one below.
<a href="file_to_download.txt">Download</a>
Also Check Countdown timer before displaying download link or hyperlink using javascript
But to make it more complex and hide the location of files (If you add some encryption techniques, Not explained in this tutorial) you can make use PHP and a little javascript. All we are doing here is create a simple Javascript function and use window.location to call the PHP file.
Lets make a javascript function named download(), Create a html file with the name getfile.html and add the below javascript and html.
<script type="text/javascript"> function download(filename) { window.location="Download.php?path="+filename;; } </script>
Now copy the below html to call the javascript function above.
<a href="javascript:download('myfile.txt')">Download</a>
The content of Download.php file will be like the one below.
<?php header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=".$_GET['path']); readfile($_GET['path']); ?>
Make sure you copy the getfile.html and Download.php file in the same location. You can always modified the file path accordingly. Happy Coding!!! 🙂