How to implement file download in php

王林
Release: 2023-03-01 06:50:01
Original
2296 people have browsed it

How to implement file download in php

Use the head() and fread() functions to output the file directly to the browser.

Specific code:

<?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 ();    
}
Copy after login

For more related tutorials, please pay attention to php Chinese website.

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template