How php downloads various files

Source: Internet
Author: User
If we only use & lt; ahref & amp; #39; file path/file name & amp; #39; & gt; download & lt;/a & gt; or js window. location & amp; #39; file path/file name & amp; #39; and the file type is recognizable by the browser, the browser will open the file directly instead of pop-up the download box to download the file, for example...

If we only use the download or js window. location = 'File path/upload', '. Conf','. bin', and so on. Of course, the document.execcommand('saveas', 'mycodes.txt ') (the second parameter is the file name to be saved) of JS can also be downloaded, but its compatibility is poor and firefox is invalid. If your environment supports the php language, you can use header () to download files:

Let's look at a simple example first:

There are two files in the same directory: index.php, test.php, and the download file adam.txt:

Test. php file content:

$ Filename = 'adam.txt ';
Echo "download ";

?>

Index. php file content:

$ Filename = $ _ REQUEST ['filename'];

Header ("Content-Type: text/plain ");
Header ('content-Disposition: attachment; filename = '. $ filename );
Header ('content-Transfer-Encodeing: binary ');
Readfile ($ filename );

?>

When you open test.php and perform a single download, you can download the adam.txt file.

Likewise, we can download files such as .jpg, .zip, .rar, and plain. in this case, we only need to modify the header ("Content-Type: text/plain") in index. php, as shown below:

Header ("Content-Type: application/zip"); // zip or rar

Header ("Content-Type: application/pdf"); // pdf

Header ("Content-Type: image/jpeg"); // image

Header ("Content-Type: audio/mpeg ");


From adamboy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.