Home Backend Development PHP Problem How to download files in php [Summary]

How to download files in php [Summary]

Aug 18, 2020 am 10:49 AM
php

How to download files in php: 1. Get the file path from "$_GET['file']"; 2. Set the header information; 3. Use the "file_get_contents()" and "file()" methods; 4. Through the "readfile" and "fopen" methods.

How to download files in php [Summary]

Recommended: "PHP Video Tutorial"

How to download files in PHP

1. Get the file path

Get the file path from $_GET['file']

$path_parts = pathinfo($_GET['file']);
$file_name  = $path_parts['basename'];
$file_path  = '/mysecretpath/' . $file_name;
Copy after login

Be sure to use the above method to get the path. You cannot simply concatenate strings to get the path.

$mypath = '/mysecretpath/' . $_GET['file'];
Copy after login

If the input is ../../, you can access any path

2. Set header information

header('Content-Description: File Transfer'); //描述页面返回的结果
header('Content-Type: application/octet-stream'); //返回内容的类型,此处只知道是二进制流。具体返回类型可参考http://tool.oschina.net/commons
header('Content-Disposition: attachment; filename='.basename($file));//可以让浏览器弹出下载窗口
header('Content-Transfer-Encoding: binary');//内容编码方式,直接二进制,不要gzip压缩
header('Expires: 0');//过期时间
header('Cache-Control: must-revalidate');//缓存策略,强制页面不缓存,作用与no-cache相同,但更严格,强制意味更明显
header('Pragma: public');
header('Content-Length: ' . filesize($file));//文件大小,在文件超过2G的时候,filesize()返回的结果可能不正确
Copy after login

3. Output file file_get_contents() method

file_get_contents() reads the file contents into a string, that is, reads the file into the memory and then outputs the content

$str = file_get_contents($file);
echo $str;
Copy after login

In this way, as long as the file is slightly larger, it will Memory limit exceeded

4. The file() method of output file

is similar to file_get_contents(), except that file() will read the contents into the array line by line, and it also needs to occupy Memory

$f = file($file);
while(list($line, $cnt) = each($f)) {
   echo $cnt;
}
Copy after login

When the file is large, it will exceed the memory limit

5. Readfile() method of output file

readfile() method: read a file and write To the output buffer

This method can directly output to the buffer without the entire file occupying memory

The prerequisite is to clear the buffer first and let the user see the dialog box for downloading the file

while (ob_get_level()) ob_end_clean();
//设置完header以后
ob_clean();
flush();  //清空缓冲区
readfile($file);
Copy after login

This method can output large files, and reading a single file will not exceed the memory limit, except for the following situations.

readfile() will also cause PHP memory exhaustion when multiple people read the file: http://stackoverflow.com/questions/6627952/why-does-readfile-exhaust-php- memory

PHP has to read the file and it writes to the output buffer. So, for 300Mb file, no matter what the implementation you wrote (by many small segments, or by 1 big chunk) PHP has to read through 300Mb of file eventually.

If multiple user has to download the file, there will be a problem. (In one server, hosting providers will limit memory given to each hosting user. With such limited memory, using buffer is not going to be a good idea. )

I think using the direct link to download a file is a much better approach for big files.

The main idea: PHP needs to read the file , and then output to the buffer. For a 300M file, PHP still has to read 300M of memory. Therefore, when multiple users are downloading at the same time, the buffer will also run out of memory. (Please correct me if I am wrong)

For example, if 100 users are downloading, they will need 100*buffer_size memory

6. The fopen() method of output file

set_time_limit(0);
$file = @fopen($file_path,"rb");
while(!feof($file))
{
    print(@fread($file, 1024*8));
    ob_flush();
    flush();
}
Copy after login

fopen () can read large files, and you can specify a part of the content to be read each time. It is also useful when operating large files

7. Summary

When using PHP to download files, you should pay attention to the scenario. If only a few small files are being downloaded, it is better to use PHP to download; but if PHP has to withstand a large number of download requests, then the file downloading should not be done by PHP.

For Apache, mod_xsendfile can help complete the download task, which is simpler and faster

The above is the detailed content of How to download files in php [Summary]. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles