We often download various files through web pages, how do we achieve this? This article discusses file downloading from the perspective of PHP, combined with http-related content.
Generally speaking, files can be downloaded directly through hyperlinks.
<span><</span><span>a </span><span>href</span><span>='要下载的文件'</span><span>></span>点击下载<span></</span><span>a</span><span>><br /></span>
This method can handle many formats of files such as .exe, .rar and other formats, but for image formats, html, txt and other types of files, clicking the link will only be displayed directly on the browser. So how to deal with this situation? At this time, php needs to appear.
In my limited PHP programming experience, I have encountered two forms of PHP download files. On the whole, file downloading is achieved by setting the response header. There is no essential difference in principle.
The first type:
<em id="__mceDel"><span>$file_name='文件名'<span>;</span> </span><span>header</span> ( 'Content-Disposition: attachment; filename=' . <span>basename</span> ( <span>$file_name</span><span> )); </span><span>header</span> ( 'Content-Length: '.<span>filesize</span> ( <span>$file_name</span><span> )); </span><span>readfile</span> ( <span>$file_name</span> );</em>
Where $filename is set to the name of the downloaded file. Read a file through readfile() and write it to the output buffer.
The second type:
<span>$file_name</span>='要下载的文件名'<span>; </span><span>$fp</span>=<span>fopen</span>(<span>$file_name</span>,"r+"<span>); </span><span>$file_size</span>=<span>filesize</span>(<span>$file_name</span>); <span>//header</span>("Content-type: application/octet-stream"<span>); //返回的文件类型 </span><span>//header</span>("Accept-Ranges: bytes"<span>);//按照字节格式返回</span> <span>header</span>("Accept-Length: ".<span>$file_size</span><span>); </span><span>header</span>("Content-Disposition: attachment; filename=".<span>$file_name</span><span>);</span> <span>$buffer</span>=1024<span>; </span><span>while</span>(!<span>feof</span>(<span>$fp</span><span>)){ </span><span>$file_data</span>=<span>fread</span>(<span>$fp</span>,<span>$buffer</span><span>); </span><span>echo</span> <span>$file_data</span><span>; } </span><span>fclose</span>(<span>$fp</span>);
This method describes the process of downloading files in more detail.