Home >Backend Development >PHP Tutorial >PHP implementation file download_PHP tutorial
You will definitely laugh at me. Is it worth saying that "downloading files" is so simple? Of course it's not as simple as you think. 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, for example, the following code written by the author:
<?
// Check whether the FORM is completely filled out...
if ($form_completed) {
Header("Location: http ://www.myweb.com/download/info_check.exe");
exit;
}
?>
Or the following situation:
" <a href="http ://www.yourwebl.com/users/download.php?id=124524">Start downloading the file</a>"
Here, the ID method is used to receive the number of the file to be downloaded, and then the "Redirect" method is used Connect to the actual URL.
If you want to make an e-commerce website about "online shopping" and consider security issues, you don't want users to copy the URL directly to download the file. The author recommends that you use PHP to directly read the actual file and then download 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
// Enter 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, Then the source code will be slightly changed, 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);
}
?>
In this way, you can use PHP to output the file directly.