PHP force download a file example

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?


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Ó[email protected]ꕃ???À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]