search
HomeBackend DevelopmentPHP TutorialPHP download file forces any file format to be downloaded

Using PHP to download some files is generally necessary to hide the real download address of the file. Otherwise, it will increase the load on the server. It is better to provide the address of the software directly.

A simple php file downloads the source code. Although it does not support breakpoint resumption, etc., it can meet some common needs. PHP download files can actually be achieved with an a tag, such as magento-1.8.1.0.zip. But when you encounter some formats that the browser can recognize, such as .txt, .html, .pdf, etc., you must know what will happen if you use abc.txt again.

  1. /**
  2. * File download
  3. *
  4. **/
  5. header("Content-type:text/html;charset=utf-8");
  6. download('web/magento-1.8.1.0.zip ', 'magento download');
  7. function download($file, $down_name){
  8. $suffix = substr($file,strrpos($file,'.')); //Get the file suffix
  9. $down_name = $down_name .$suffix; //The new file name is the name after downloading
  10. //Determine whether the given file exists
  11. if(!file_exists($file)){
  12. die("The file you want to download no longer exists, It may have been deleted");
  13. }
  14. $fp = fopen($file,"r");
  15. $file_size = filesize($file);
  16. //The header needed to download the file
  17. header("Content-type : application/octet-stream");
  18. header("Accept-Ranges: bytes");
  19. header("Accept-Length:".$file_size);
  20. header("Content-Disposition: attachment; filename=".$ down_name);
  21. $buffer = 1024;
  22. $file_count = 0;
  23. //Return data to the browser
  24. while(!feof($fp) && $file_count $file_con = fread($fp, $buffer);
  25. $file_count += $buffer;
  26. echo $file_con;
  27. } www.jbxue.com
  28. fclose($fp);
  29. }
  30. ?>
Copy code

Source code for PHP mandatory file download

Provides users with mandatory file download functionality.

  1. /********************
  2. *@file - path to file
  3. */
  4. function force_download($file)
  5. {
  6. if ((isset($file))&&(file_exists($file))) {
  7. header("Content-length: " .filesize($file));
  8. header('Content-Type: application/octet-stream');
  9. header('Content-Disposition: attachment; filename="' . $file . '"');
  10. readfile( "$file");
  11. } else {
  12. echo "No file selected";
  13. }
  14. }
Copy code

You will definitely laugh at me. Is it worth saying that "downloading a file" is so simple? Of course it's not as simple as imagined. For example, if you want customers to fill out a form before they can download a certain file, your first idea must be to use the "Redirect" method. First check whether the form has been filled in and complete, and then point the URL to the file. , so that customers can download it, but if you want to make an e-commerce website about "online shopping" and consider security issues, you don't want users to directly copy the URL to download the file. The author recommends that you use PHP to directly read the actual file and then download it. method to do it. The procedure is as follows:

  1. $file_name = "info_check.exe";
  2. $file_dir = "/public/www/download/";
  3. if (!file_exists($file_dir . $file_name)) { //Check whether the file exists
  4. echo " File not found";
  5. exit;
  6. } else {
  7. $file = fopen($file_dir . $file_name,"r"); // Open the file
  8. // Enter the file tag www.jbxue.com
  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 content
  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, the source code will be slightly changed. The procedure is as follows:

  1. $file_name = "info_check.exe";
  2. $file_dir = "http://www.jbxue.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. }
Copy code

This way you can directly output the file using PHP.

However, be sure to note: Header information is equivalent to first browsing the file information at high speed, and then downloading the information on the browser to the attachment. Therefore, if you are in an MVC-mode application, the view page must not have any content. Otherwise, the relevant content of the view page will be downloaded together with the content of the file, resulting in the downloaded file being unusable.
Here is my program:

  1. public function downloadAction()
  2. {
  3. if (isset($_GET['mriID']))
  4. {
  5. $this->view->mriID=(get_magic_quotes_gpc())?$_GET['mriID ']:addslashes($_GET['mriID']);
  6. }
  7. if (isset($_GET['dicomID']))
  8. {
  9. $this->view->dicomID=(get_magic_quotes_gpc())? $_GET['dicomID']:addslashes($_GET['dicomID']);
  10. }
  11. if (isset($_GET['JPGID']))
  12. {
  13. $this->view->JPGID=( get_magic_quotes_gpc())?$_GET['JPGID']:addslashes($_GET['JPGID']);
  14. } www.jbxue.com
  15. $dicomfile=new dicomfile();
  16. $jpgfile=new jpgfile();
  17. $mri=new mri();
  18. if($this->view->dicomID)
  19. {
  20. $filename=$dicomfile->find($this->view->dicomID)->toArray ();
  21. $filename=$filename[0]['filename'];
  22. }
  23. else if($this->view->JPGID)
  24. {
  25. $filename=$jpgfile->find($this ->view->JPGID)->toArray();
  26. $filename=$filename[0]['JPGname'];
  27. }
  28. $dir=$mri->find($this->view ->mriID)->toArray();
  29. $dir=$dir[0]['dicom_path'];
  30. $file=$dir.'/'.$filename;
  31. if (!file_exists($file) )
  32. {
  33. echo "the file does not exist!";
  34. exit();
  35. }
  36. $file_size=filesize($file);
  37. header("Content-type: application/octet-stream");
  38. header( "Accept-Ranges: bytes");
  39. header("Accept-Length:". $file_size);
  40. header("Content-Disposition: attachment; filename=".$filename);
  41. $fp=fopen($file, "r");
  42. if (!$fp)
  43. echo "can't open file!";
  44. $buffer_size=1024;
  45. $cur_pos=0;
  46. while (!feof($fp)&&$file_size-$cur_pos> ;$buffer_size)
  47. {
  48. $buffer=fread($fp,$buffer_size);
  49. echo $buffer;
  50. $cur_pos+=$buffer_size;
  51. }
  52. $buffer=fread($fp,$file_size-$cur_pos);
  53. echo $buffer;
  54. fclose($fp);
  55. }
Copy code

At this point, the download.phtml page must be completely blank. Never include any content (including canned messages like:

  1. Untitled Document) Otherwise, this information will be downloaded into the download file, rendering the file unusable.
Copy code



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools