Open In App

How to force a file to get downloaded in PHP?

To force a file to get downloaded, there is no need to use the PHP script if you want to keep it simple. If such kind of file is stored in a publicly accessible folder, just create a hyperlink pointing to that file. When the user clicks the file link then the file will be downloaded. You can check the first example of how to trigger a file download when clicking an HTML button article.

Forcing a file to download using PHP: We will be using PHP here as the server-side scripting language. In PHP, this can be done by using readfile() function. The main function of readfile() is to output a file. On clicking any of the hyperlinks the respective file will be downloaded by the browser as shown. The regular expression(regex) validation in the above example using preg_match() function will simply not allow insertion of any illegal character.

Example: The idea is to send the file path information by URL as a parameter to the PHP file downloader.php. Where the file path information will be fed the readfile() function after checking the validity of the file. If an error arises during validation we will display a message saying, “Download cannot be processed”. Let’s create the interface for the user first in a file named index.html.


Article Tags :