Heim > php教程 > php手册 > Hauptteil

PHP+Mysql+jQuery文件下载次数统计实例讲解,

WBOY
Freigeben: 2016-06-13 08:53:25
Original
1073 Leute haben es durchsucht

PHP+Mysql+jQuery文件下载次数统计实例讲解,

项目中我们需要统计文件的下载次数,用户每下载一次文件,相应的下载次数加1,类似的应用在很多下载站中用到。本文结合实例使用PHP+Mysql+jQuery,实现了点击文件,下载文件,次数累加的过程,整个过程非常流畅。

准备工作
本实例需要读者具备PHP、Mysql、jQuery以及html、css等相关的基本知识,在开发示例前,需要准备Mysql数据表,本文假设有一张文件下载表downloads,用来记录文件名、保存在文件服务器上的文件名以及下载次数。前提是假设下载表中已存在数据,这些数据可能来自项目中的后台上传文件时插入的,以便我们在页面中读取。downloads表结构如下:

CREATE TABLE IF NOT EXISTS `downloads` ( 
 `id` int(6) unsigned NOT NULL AUTO_INCREMENT, 
 `filename` varchar(50) NOT NULL, 
 `savename` varchar(50) NOT NULL, 
 `downloads` int(10) unsigned NOT NULL DEFAULT '1', 
 PRIMARY KEY (`id`), 
 UNIQUE KEY `filename` (`filename`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 
Nach dem Login kopieren

您也可以直接下载Demo,导入SQL文件,数据都有了。
HTML
我们在index.html页面body中加入如下HTML结构,其中ul.filelist用来陈列文件列表,现在它里面没有内容,我们将使用jQuery来异步读取文件列表,所以别忘了,我们还需要在html中加载jQuery库文件。

<div id="demo"> 
  <ul class="filelist"> 
  </ul> 
</div> 
Nach dem Login kopieren

CSS
为了让demo更好的展示页面效果,我们使用CSS来修饰页面,以下的代码主要设置文件列表展示效果,当然实际项目中可以根据需要设置相应的样式。

#demo{width:728px;margin:50px auto;padding:10px;border:1px solid #ddd;background-color:#eee;} 
ul.filelist li{background:url("img/bg_gradient.gif") repeat-x center bottom #F5F5F5; 
border:1px solid #ddd;border-top-color:#fff;list-style:none;position:relative;} 
ul.filelist li.load{background:url("img/ajax_load.gif") no-repeat; padding-left:20px; 
border:none; position:relative; left:150px; top:30px; width:200px} 
ul.filelist li a{display:block;padding:8px;} 
ul.filelist li a:hover .download{display:block;} 
span.download{background-color:#64b126;border:1px solid #4e9416;color:white; 
display:none;font-size:12px;padding:2px 4px;position:absolute;right:8px; 
text-decoration:none;text-shadow:0 0 1px #315d0d;top:6px; 
-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;} 
span.downcount{color:#999;padding:5px;position:absolute; margin-left:10px;text-decoration:none;} 
Nach dem Login kopieren

PHP
为了更好的理解,我们分两个PHP文件,一个是filelist.php,用来读取mysql数据表中的数据,并输出为JSON格式的数据用来给前台index.html页面调用,另一个是download.php,用来响应下载动作,更新对应文件的下载次数,并且通过浏览器完成下载。filelist.php读取downloads表,并通过json_encode()将数据以JSON格式输出,这样是为下面的Ajax异步操作准备的。

require 'conn.php'; //连接数据库 
$result = mysql_query("SELECT * FROM downloads"); 
if(mysql_num_rows($result)){ 
  while($row=mysql_fetch_assoc($result)){ 
    $data[] = array( 
      'id' => $row['id'], 
      'file' => $row['filename'], 
      'downloads'=> $row['downloads'] 
    ); 
  } 
  echo json_encode($data); 
} 
Nach dem Login kopieren

download.php根据url传参,查询得到对应的数据,检测要下载的文件是否存在,如果存在,则更新对应数据的下载次数+1,并且使用header()实现下载功能。值得一提的是,使用header()函数,强制下载文件,并且可以设置下载后保存到本地的文件名称。一般情况下,我们通过后台上传程序会将上传的文件重命名后保存到服务器上,常见的有以日期时间命名的文件,这样的好处之一就是避免了文件名重复和中文名称乱码的情况。而我们下载到本地的文件可以使用header("Content-Disposition: attachment; filename=" .$filename )将文件名设置为易于识别的文件名称。

require('conn.php');//连接数据库 
$id = (int)$_GET['id']; 
 
if(!isset($id) || $id==0) die('参数错误!'); 
$query = mysql_query("select * from downloads where id='$id'"); 
$row = mysql_fetch_array($query); 
if(!$row) exit; 
$filename = iconv('UTF-8','GBK',$row['filename']);//中文名称注意转换编码 
$savename = $row['savename']; //实际在服务器上的保存名称 
$myfile = 'file/'.$savename; 
if(file_exists($myfile)){//如果文件存在 
  //更新下载次数 
  mysql_query("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); 
  } 
  fclose($file); 
  exit; 
}else{ 
  echo '文件不存在!'; 
} 
Nach dem Login kopieren

jQuery
前端页面jQuery主要完成两个任务,一是通过Ajax异步读取文件列表并展示,二是响应用户点击事件,将对应的文件下载次数+1,来看代码:

$(function(){ 
  $.ajax({ //异步请求 
    type: 'GET', 
    url: 'filelist.php', 
    dataType: 'json', 
    cache: false, 
    beforeSend: function(){ 
      $(".filelist").html("<li class='load'>正在载入...</li>"); 
    }, 
    success: function(json){ 
      if(json){ 
        var li = ''; 
        $.each(json,function(index,array){ 
          li = li + '<li><a href="download.php&#63;id='+array['id']+'">'+array['file']+ 
'<span class="downcount" title="下载次数">'+array['downloads']+'</span> 
<span class="download">点击下载</span></a></li>'; 
        }); 
        $(".filelist").html(li); 
      } 
    } 
  }); 
  $('ul.filelist a').live('click',function(){ 
    var count = $('.downcount',this); 
    count.text( parseInt(count.text())+1); //下载次数+1 
  }); 
}); 
Nach dem Login kopieren

首先,页面载入完后,通过$.ajax()向后台filelist.php发送一个GET形式的Ajax请求,当filelist.php相应成功后,接收返回的json数据,通过$.each()遍历json数据对象,构造html字符串,并将最终得到的字符串加入到ul.filelist中,形成了demo中的文件列表。
然后,当点击文件下载时,通过live()响应动态加入的列表元素的click事件,将下载次数进行累加。
最后,其实通读本文,这就是一个我们通常应用到的Ajax案例,当然还有PHP结合mysql实现下载的知识,希望对大家有所帮助。

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!