Home  >  Article  >  Backend Development  >  What to use to download files in php

What to use to download files in php

藏色散人
藏色散人Original
2019-10-11 10:14:582897browse

What to use to download files in php

#What do you use to download files in php?

The head() and fread() functions output the file directly to the browser. This method can better hide the real address of the file.

<?php  
$file_name = "down";$file_name = "down.zip";     
//下载文件名    
$file_dir = "./down/";       
 //下载文件存放目录    
//检查文件是否存在    
if (! file_exists ( $file_dir . $file_name )) {    
    header(&#39;HTTP/1.1 404 NOT FOUND&#39;);  
} 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:

The file exists

What to use to download files in php

The file does not exist

What to use to download files in php

For more PHP related knowledge, please visit PHP中文网!

The above is the detailed content of What to use to download files in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn