Home > Backend Development > PHP Tutorial > PHP implements safe file download_PHP tutorial

PHP implements safe file download_PHP tutorial

WBOY
Release: 2016-07-21 16:09:56
Original
730 people have browsed it

You will definitely laugh at me. Is it worth saying that "downloading a file" is so simple? Of course it's not as simple as imagined. For example, if you want customers to fill out a form before they can download a certain file, your first idea must be to use the "Redirect" method. First check whether the form has been filled in and complete, and then point the URL to the file. , so that customers can download it, but if you want to make an e-commerce website about "online shopping" and consider security issues, you don't want users to directly copy the URL to download the file. The author recommends that you use PHP to directly read the actual file and then download it. method to do it. The program is as follows:

$file_name = "info_check.exe";
$file_dir = "/public/www/download/";
if (!file_exists($file_dir . $file_name)) { //Check if the file exists
echo "File not found";
exit;
} else {
$file = fopen($file_dir . $file_name,"r"); // Open File
//Input 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;}

And if the file path is an "http" or "ftp" URL, the source code will There are a few changes, the procedure is as follows:

$file_name = "info_check.exe";
$file_dir = "http://www.easycn.net/";
$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);
}

This way you can use PHP to directly output the file.​

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314359.htmlTechArticleYou will definitely laugh at me. Is it worth saying that downloading a file is so easy? Of course it's not as simple as imagined. For example, if you want customers to fill out a form before they can download a certain file, your first thought...
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