Home > Article > Backend Development > PHP file download example code_PHP tutorial
php tutorial file download example code
function xiazai($file_dir,$file_name)
//Parameter description:
//file_dir: the directory where the file is located
//file_name: file name
{
$file_dir = chop($file_dir);//Remove extra spaces in the path
//Get the path of the file to be downloaded
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 be downloaded exists if(!file_exists ($file_path))
{
alert('Sorry, the file you want to download does not exist');
return false;
}
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;
echo $cur_pos += $buffer_size;
}
$buffer = fread($fp,$file_size-$cur_pos); $buffer;
fclose($fp);
return true;
}
http://www.bkjia.com/PHPjc/444963.html