Home  >  Article  >  Backend Development  >  How to download files in php [Summary]

How to download files in php [Summary]

藏色散人
藏色散人Original
2020-08-18 10:49:038792browse

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;

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

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

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()返回的结果可能不正确

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;

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;
}

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);

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();
}

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:
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