How to automatically start a download in PHP ?

This post deals with creating a start downloading file using PHP. The idea is to make a download button which will redirect you to another page with the PHP script that will automatically start the download.

Creating a download button:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <meta name="viewport" content=
        "width=device-width, initial-scale=1">
    <style>
        .btn {
            background-color: limeGreen;
            border: none;
            color: white;
            padding: 12px 30px;
            cursor: pointer;
            font-size: 20px;
        }
  
        .btn:hover {
            background-color: green;
        }
    </style>
</head>
  
<body>
    <center>
        <p>Auto width:</p>
        <button class="btn">
            <i class="fa fa-download">Download</i>
        </button>
        <p>Full width:</p>
        <button class="btn" style="width:100%">
            <i class="fa fa-download">Download</i>
        </button>
    </center>
</body>
  
</html>

chevron_right


Output:

To redirect to some file which has the file to be downloaded, create an HTML form as shown below.

filter_none

edit
close

play_arrow

link
brightness_4
code

<form action="downloadFile.php" method="post">
 <input type="submit" name="submit" value="Download" />
</form>

chevron_right


Output:



PHP code to download: When the user clicks the above button, the code will be redirected to the “downloadFile.php” file. Now, use the URL of the file and PHP file_get_contents() function to download the file.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
    
// Initialize a file URL to 
// the variable 
$url
    
// Use basename() function to 
// return the file  
$file_name = basename($url); 
     
// Use file_get_contents() function 
// to get the file from url and use 
// file_put_contents() function to 
// save the file by using base name 
if(file_put_contents( $file_name
      file_get_contents($url))) { 
    echo "File downloaded successfully"
else
    echo "File downloading failed."
}
?> 

chevron_right


Output:

  • Before running the program:
  • After running the program:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.