欢迎光临
我们一直在努力

PHP实现文件下载-PHP教程,PHP应用

建站超值云服务器,限时71元/月

你一定会笑我“下载文件”如此简单都值得说?当然并不是想你想象的那么简单。例如你希望客户要填完一份表格,才可以下载某一文件,你第一个想法一定是用 “redirect”的方法,先检查表格是否已经填写完毕和完整,然后就将网址指到该文件,这样客户才能下载,例如笔者编写的以下代码:

<?
// 检查 form 是否全部填写完毕…
if ($form_completed) {
header(“location: http://www.myweb.com/download/info_check.exe”);
exit;
}
?>

或者是以下的情况:

“ <a href=”http://www.yourwebl.com/users/download.php?id=124524″>开始下载文件</a> ”

这里利用了id方式接收要下载文件的编号,然后用“redirect”的方式连接到实际的网址。

如果你想做一个关于“网上购物”的电子商务网站,考虑安全问题,你不想用户直接复制网址下载该文件,笔者建议你使用php直接读取该实际文件然后下载的方法去做。程序如下:

<?
$file_name = “info_check.exe”;
$file_dir = “/public/www/download/”;
if (!file_exists($file_dir . $file_name)) { //检查文件是否存在
echo “文件找不到”;
exit;
} else {
$file = fopen($file_dir . $file_name,”r”); // 打开文件
// 输入文件标签
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);
// 输出文件内容
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit;}
?>

而如果文件路径是“http”或者“ftp” 网址的话,则源代码会有少许改变,程序如下:

<?
$file_name = “info_check.exe”;
$file_dir = “http://www.easycn.net/”;
$file = @ fopen($file_dir . $file_name,”r”);
if (!$file) {
echo “文件找不到”;
} else {
header(“content-type: application/octet-stream”);
header(“content-disposition: attachment; filename=” . $file_name);
while (!feof ($file)) {
echo fread($file,50000);
}
fclose ($file);
}
?>

这样就可以用php直接输出文件了。 

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » PHP实现文件下载-PHP教程,PHP应用
分享到: 更多 (0)