How to download files in PHP

Source: Internet
Author: User
Tags php download hosting
How to download files in PHP

1. Get the file path

Get 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 method above to get the path, not simple string concatenation 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 '); Describes the results returned by the page header (' Content-type:application/octet-stream '); Returns the type of content that is only known here as a binary stream. The specific return type can refer to Http://tool.oschina.net/commonsheader (' content-disposition:attachment; Filename= '. basename ($file));// Can let the browser pop up the download window header (' content-transfer-encoding:binary ');//Content encoding method, direct binary, do not gzip compressed header (' expires:0 ');//Expiry time Header (' cache-control:must-revalidate ');//cache policy, forcing the page not to cache, acting the same as No-cache, but more strictly, forcing a more pronounced header (' pragma:public '); Content-length: '. FileSize ($file));//File size, filesize () may not return the correct result when the file exceeds 2G

3. File_get_contents () method of the output file

File_get_contents () reads the contents of the file into a string, that is, to read the file into memory, and then output the contents

$str = file_get_contents ($file); Echo $str;

This way, as long as the file is a little larger, it will exceed the memory limit

4. File () method for output files

Similar to file_get_contents (), except that file () reads the content into the array in rows and takes up memory

$f = File ($file), while (List ($line, $cnt) = each ($f)) {   echo $cnt;}

Memory limit is exceeded when the file is large

5. ReadFile () method of the output file

ReadFile () Method: read in a file and write to output buffer
This method can be output directly to the buffer, not the entire file consumption memory
If you want to clear the buffer first, let the user see the Download file dialog box

while (Ob_get_level ()) Ob_end_clean ();//After the header is set Ob_clean (); flush ()  ; Emptying buffer ReadFile ($file);

This method outputs large files and does not cause failures due to memory reasons.
But ReadFile () also causes PHP to run out of memory: http://stackoverflow.com/questions/6627952/why-does-readfile-exhaust-php-memory

PHP has-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 have to Rea D through 300Mb of file eventually.

If multiple user have to download the file, there'll be a problem. (in one server, hosting providers would limit memory given to each hosting user.) With such limited memory, the using buffer is not going to being a good idea. )
I think using the direct link to download a file are a much better approach for big files.

PHP needs all the files, and then output to the buffer. For a 300M file, PHP will eventually read 300M of memory. Therefore, when multiple users download at the same time, the buffer will also run out of memory. (No, please correct it.)

For example, 100 users in the download, need 100*buffer_size size of memory

6. fopen () method of the 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 into large files, and can specify what part of the content is read at a time. Also useful when working with large files

7. Summary

When using PHP to download files, you should focus on the scene. If it is only a few small files are downloaded, then php download is better, but if PHP to withstand a large number of download requests, then download the file should not be given to PHP.

For Apache, Mod_xsendfile can help with download tasks, simpler and faster

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