- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to force file download with PHP?
The below code can be used to force a file to get downloaded in PHP.
<?php header('Content-type: text/javascript'); header('Content-Disposition: attachment; filename="file.js"'); readfile(file that is downloaded.js'); //This can be printed for verification purpose ?>
NOTE − This needs to be done before displaying any output, otherwise the file will have output from other operations as well (which might be irrelevant).
Another method that could be used is to use the .htaccess solution. In this method, all the files on the server can be forced to be downloaded, and can be added to the .htaccess file. This has been demonstrated below −
AddType application/octet-stream csv header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename=name of csv file'); header('Pragma: no-cache'); readfile("path-to-csv-file");
Advertisements