PHP force download a file example

0

PHP allows you to change the HTTP Headers of files that you’re writing, so that you can force a file to be downloaded that normally the browser would load in the same window.
Following php script will give to force download a file using php.

The MIME(Multipurpose Internet Mail Extensions) specifications only described the structure of mail messages.You can read about the MIME type from this link.

Some peoples may be argue that attackers can be download index.php, header.php such db connection files.But above switch statement is checking that you want to download file type.So it is secure.

How to use this?


href="domainName/downloadFile.php?file=Students_Marks.pdf"

Note:-Sometimes your file will get an error as follows.
Warning: Cannot modify header information - headers already sent by (output started......
%PDF-1.3 %âã??Ó 1 0 obj << /Filter[/FlateDecode] /Length 750 >> stream X…‘??OÓp@oꕃ???Àv’ ˜Õ?Øg›@bY·²Äƒ™k»Edë¯0‚??Œ¶ L¦]»#¶n|D!e° 11???&4•àXâÅŸzpÇ]%¾ä??_òlnÂNWÑþKÈ??V³? ]]N×…»:®ÚÌF£å¢)ÄÓç"??MûyÊ??†F†ƒBLXüxÿ¹Üé¦0’–ÒZõøW~Gx*¶¢Úp§ÉËØ)@øÙî'‚?ÜÈj•B¾òI¯Ã„ÿ=…Nj?•µ½ñÔî³¥íåÒ×µÔn1úzYYË&d9‘??Sïh–£,‚c]

Notice if already have spaces at the beginning of the script like following diagram:
Warning: Cannot modify header information - headers already sent by (output started

Solution: Remove all spaces at the beginning of the script.

View Demo

Download PHP force download a file Example (32 KB)

Share.

About Author

Sumith Harshan is the Web Engineer Specializes in Java Script, JQuery, HTML4/5, CSS2/3, PHP, CodeIgniter, CakePHP, J2SE, J2EE, XML, Hacking & Security, Mobile Interface Developing, Magento, Wordpress, Joomla, Drupal,PHPBB,Facebook App Developing and Open cart...etc.