Home >Backend Development >PHP Tutorial >PHP file download code (supports remote file download)_PHP tutorial
PHP file download code (supports remote file download)/*Two of the three file download codes provided in this article support local server file downloads, and the other supports downloading files on remote servers to the local.
php tutorial file download code (supports remote file download)
/*
Two of the three file download codes provided in this article support local server file downloads, and the other supports downloading on remote servers Download the file locally.
*/
$file_name = "info_check.exe";function download($file_dir,$file_name)
header("accept-ranges: bytes");
//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; !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-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;
}
?>
$file_dir = "/public/www/download/ ";
if (!file_exists($file_dir . $file_name)) { //Check if the file exists
exit;
} else {
$ file = fopen($file_dir . $file_name,"r"); // Open the file
// Enter the file tag
header("content-type: application/octet-stream");
header( "accept-ranges: bytes");
header("accept-length: ".filesize($file_dir . $file_name));
header("content-disposition: attachment; filename=" . $file_name) ;
// Output file content
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit;}
?>
// If the file path is http and ftp, the download code is as follows:
$file_dir = " http://www.bkjia.com/";
$file = @ fopen($file_dir . $file_name,"r");if (!$file) {echo "File not found";
} else {
header("content-type: application/octet-stream");
header("content- disposition: attachment; filename=" . $file_name);
while (!feof ($file)) {
echo fread($file,50000);
}
fclose ($file);
}
?>