Implement file download with PHP

Source: Internet
Author: User
Tags fread header implement strlen
Download if only ordinary file download, there is no need to use PHP, with a <a href= ' Http://xx.xx.com/xx.tar ' ></a> can, but sometimes to keep files confidential, can only be downloaded to some people, Obviously not be able to tell others about the link, if this is not the effect of confidentiality.

The following function is a PHP-written file to download the function, it is a section of the file read out, and then sent to the client.

function Download ($file _dir, $file _name)
Parameter description:
File_dir: directory where files reside
file_name: filename
{
$file _dir = Chop ($file _dir);//Remove extra spaces from the path
The path to the file to download
if ($file _dir!= ')
{
$file _path = $file _dir;
if (substr ($file _dir,strlen ($file _dir) -1,strlen ($file _dir))!= '/')
$file _path. = '/';
$file _path. = $file _name;
}
Else
$file _path = $file _name;

Determine if the file you want to download exists
if (!file_exists ($file _path))
{
Echo ' Sorry, the file you are downloading does not exist. ';
return false;
}

$file _size = filesize ($file _path);

Header ("Content-type:application/octet-stream");
Header ("Accept-ranges:bytes");
Header ("Accept-length: $file _size");
Header ("content-disposition:attachment; Filename= ". $file _name);

$fp = fopen ($file _path, "R");
$buffer _size = 1024;
$cur _pos = 0;

while (!feof ($fp) && $file _size-$cur _pos> $buffer _size)
{
$buffer = Fread ($fp, $buffer _size);
Echo $buffer;
$cur _pos + + $buffer _size;
}

$buffer = Fread ($fp, $file _size-$cur _pos);
Echo $buffer;
Fclose ($FP);
return true;

}



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.