php file download code

Source: Internet
Author: User
Keywords Network programming PHP tutorial
Tags browser client code directory download echo file file download

This article provides you with this php tutorial file download code is a use of the header to send the file code to the client's browser to download Oh.

<?
function download ($ file_dir, $ file_name)
//Parameter Description:
// file_dir: directory of the file
// file_name: file name
{
$ file_dir = chop ($ file_dir); / / Remove extra space in the path
// Get the path of 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 whether the file to download exists
if (! file_exists ($ file_path))
{
echo 'Sorry, the file you want to download does not exist. ';
return false;
}

$ file_size = filesize ($ file_path);

header ("Content-type: application / octet-stream");
header ("Accept-Ranges: bytes"); // jzread.com
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;

}

?>

Related Article

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.