php How to download files, php file download the correct method

Source: Internet
Author: User
    1. Check if the form is complete ...
    2. if ($form _completed) {
    3. Header ("Location:http://www.myweb.com/download/info_check.exe");
    4. Exit
    5. }
    6. ?>
    7. Or:
    8. Start Download file
Copy Code

The ID is used here to receive the number of the file to download, and then "Redirect" the way to connect to the actual URL.

For security reasons, do not let users directly copy the URL to download the file, it is recommended to use PHP directly read the actual file and then download.

Code:

    1. $file _name = "Info_check.exe";
    2. $file _dir = "/public/www/download/";
    3. if (!file_exists ($file _dir. $file _name)) {//check if file exists
    4. echo "File not found";
    5. Exit
    6. } else {
    7. $file = fopen ($file _dir. $file _name, "R"); Open File
    8. Input File Label
    9. Header ("Content-type:application/octet-stream");
    10. Header ("Accept-ranges:bytes");
    11. Header ("Accept-length:". FileSize ($file _dir. $file _name));
    12. Header ("content-disposition:attachment; Filename= ". $file _name);
    13. Output file contents
    14. Echo fread ($file, FileSize ($file _dir. $file _name));
    15. Fclose ($file);
    16. Exit;}
    17. ?>
Copy Code

If the file path is "http" or "FTP" URL, then the source code will change a little, the program is as follows:

    1. $file _name = "Info_check.exe";
    2. $file _dir = "http://www.jincai123.com/";
    3. $file = @ fopen ($file _dir. $file _name, "R");
    4. if (! $file) {
    5. echo "File not found";
    6. } else {
    7. Header ("Content-type:application/octet-stream");
    8. Header ("content-disposition:attachment; Filename= ". $file _name);
    9. while (!feof ($file)) {
    10. Echo fread ($file, 50000);
    11. }
    12. Fclose ($file);
    13. }
    14. ?>
Copy Code

Using the above code, you can directly output files in PHP.

  • 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.