Home >Backend Development >PHP Tutorial >How Can I Force File Downloads in PHP?
When clicking a link to download a CSV file, users often face the issue of the file opening in the browser instead of downloading. This problem stems from the default behavior of servers, which is to display text files within the browser. To force the download, PHP provides several solutions.
For a global solution, add the following line to your .htaccess file:
AddType application/octet-stream csv
This instructs the server to treat all CSV files as binary data that should be downloaded as-is, regardless of the user's browser settings.
Alternatively, you can manually handle the download within PHP by adding the following code:
header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename=example.csv'); header('Pragma: no-cache'); readfile("/path/to/yourfile.csv");
This code:
The above is the detailed content of How Can I Force File Downloads in PHP?. For more information, please follow other related articles on the PHP Chinese website!