PHP开发实现下载次数统计功能模块(二)

创建download.php文件,用来响应下载动作,更新对应文件的下载次数,并且通过浏览器完成下载。

根据url传参,查询得到对应的数据,检测要下载的文件是否存在,如果存在,则更新对应数据的下载次数+1,数据库中的文件下载次数+1,并且使用header()实现下载功能。如果文件不存在,则输出“文件不存在!”。

值得一提的是,使用header()函数,强制下载文件,并且可以设置下载后保存到本地的文件名称。

一般情况下,我们通过后台上传程序会将上传的文件重命名后保存到服务器上,常见的有以日期时间命名的文件,这样的好处之一就是避免了文件名重复和中文名称乱码的情况。而我们下载到本地的文件可以使用header("Content-Disposition: attachment; filename=" .$filename )将文件名设置为易于识别的文件名称。

<?php
require('conn.php');
$id = (int)$_GET['id'];

if(!isset($id) || $id==0) die('参数错误!');
$query = mysqli_query($link,"select * from downloads where id='$id'");
$row = mysqli_fetch_array($query);
if(!$row) exit;
$filename = iconv('UTF-8','GBK',$row['filename']);//中文名称注意转换编码
$savename = $row['savename']; //实际在服务器上的保存名称
$myfile = 'files/'.$savename;  //文件名称
if(file_exists($myfile)){
   mysqli_query($link,"update downloads set downloads=downloads+1 where id='$id'");
   $file = @fopen($myfile, "r"); 
   header("Content-type: application/octet-stream");
   header("Content-Disposition: attachment; filename=" .$filename );
   while (!feof($file)) {
      echo fread($file, 50000);  //打开文件最大字节数为50000
   }
   fclose($file);
   exit;
}else{
   echo '文件不存在!';
}
?>

注释:

iconv函数库能够完成各种字符集间的转换,是php编程中不可缺少的基础函数库。

file_exists() 函数检查文件或目录是否存在。如果指定的文件或目录存在则返回 true,否则返回 false。

fopen() 函数打开文件或者 URL。如果打开失败,本函数返回 FALSE。“r”只读方式打开,将文件指针指向文件头。

feof() 函数检测是否已到达文件末尾 (eof)。

fread() 函数读取文件(可安全用于二进制文件)。

fclose()函数关闭一个打开文件。



继续学习
||
<?php require('conn.php'); $id = (int)$_GET['id']; if(!isset($id) || $id==0) die('参数错误!'); $query = mysqli_query($link,"select * from downloads where id='$id'"); $row = mysqli_fetch_array($query); if(!$row) exit; $filename = iconv('UTF-8','GBK',$row['filename']);//中文名称注意转换编码 $savename = $row['savename']; //实际在服务器上的保存名称 $myfile = 'files/'.$savename; //文件名称 if(file_exists($myfile)){ mysqli_query($link,"update downloads set downloads=downloads+1 where id='$id'"); $file = @fopen($myfile, "r"); header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=" .$filename ); while (!feof($file)) { echo fread($file, 50000); //打开文件最大字节数为50000 } fclose($file); exit; }else{ echo '文件不存在!'; } ?>
提交重置代码