Php file download instance code

Source: Internet
Author: User
Php file download instance code

If you use php to implement forced file download, the header function is usually used. Example: PHP file download instance.

  1. Class Downfile {
  2. Function downserver ($ file_name ){
  3. $ File_path = "./img/". $ file_name;
  4. // Transcode and convert the file name to gb2312 to solve Chinese garbled characters
  5. $ File_name = iconv ("UTF-8", "gb2312", $ file_name );
  6. $ File_path = iconv ("UTF-8", "gb2312", $ file_path );
  7. $ Fp = fopen ($ file_path, "r") or exit ("file does not exist ");
  8. // The definition variable is empty with the size of each download
  9. $ Buffer = 1024;
  10. // Get the file size
  11. $ File_size = filesize ($ file_path );
  12. // Header ("Content-type: text/html; charset = gb2312 ");
  13. // Write the four http protocols used
  14. Header ("Content-type: application/octet-stream ");
  15. Header ("Accept-Ranges: bytes"); // can be ignored
  16. Header ("Content-Length:". $ file_size); // The original text is Accept-Length. this item is not found in the http protocol.
  17. Header ("Content-Disposition: attachment; filename =". $ file_name );
  18. // Byte technician, which records the current number of bytes
  19. $ Count = 0;
  20. While (! Feof ($ fp) & $ file_size-$ count> 0 ){
  21. // Read $ buffer size data every time from the file stream opened by $ fp
  22. $ File_data = fread ($ fp, $ buffer );
  23. $ Count + = $ buffer;
  24. // Read the read data
  25. Echo $ file_data;
  26. }
  27. // Close the file stream
  28. Fclose ($ fp );
  29. }
  30. }
  31. ?>

Call this function to input a file name to download the file. pay attention to modifying $ file_path in the above code.

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.