Home > Article > Backend Development > php three ways to download files
Recommended manual:php complete self-study manual
##This article mainly shares with you three ways to download files in php. I hope Can help everyone.
<button> <a href = "http://localhost/down.zip"> 下载文件</button>
<button> <a href = "http://localhost?f='down'"> 下载文件 </button>Find the file and challenge to the download link:
<?php$down = $_GET['f']; //获取文件参数$filename = $down.'.zip'; //获取文件名称$dir ="down/"; //相对于网站根目录的下载目录路径$down_host = $_SERVER['HTTP_HOST'].'/'; //当前域名//判断如果文件存在,则跳转到下载路径if(file_exists(__DIR__.'/'.$dir.$filename)){ header('location:http://'.$down_host.$dir.$filename); }else{ header('HTTP/1.1 404 Not Found'); }Result:
<?php $file_name = "down";$file_name = "down.zip"; //下载文件名 $file_dir = "./down/"; //下载文件存放目录 //检查文件是否存在 if (! file_exists ( $file_dir . $file_name )) { header('HTTP/1.1 404 NOT FOUND'); } else { //以只读和二进制模式打开文件 $file = fopen ( $file_dir . $file_name, "rb" ); //告诉浏览器这是一个文件流格式的文件 Header ( "Content-type: application/octet-stream" ); //请求范围的度量单位 Header ( "Accept-Ranges: bytes" ); //Content-Length是指定包含于请求或响应中数据的字节长度 Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) ); //用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$file_name该变量的值。 Header ( "Content-Disposition: attachment; filename=" . $file_name ); //读取文件内容并直接输出到浏览器 echo fread ( $file, filesize ( $file_dir . $file_name ) ); fclose ( $file ); exit (); }Result: Same as the second one
The first and second operations are relatively simple, but they easily expose the real address of the file and are not very secure. The third operation can better save the file. The real address is hidden
Related article recommendations:1.How does PHP download files on the server
2.How does PHP implement it Large file download? (Code example)
3.How PHP implements file download breakpoint resume transfer
Related video recommendations
:1.Dugu Jiu Cheap (4)_PHP video tutorial
The above is the detailed content of php three ways to download files. For more information, please follow other related articles on the PHP Chinese website!