search
HomeBackend DevelopmentPHP TutorialPHP+Mysql+jQuery文件下载次数统计实例讲解_php实例

项目中我们需要统计文件的下载次数,用户每下载一次文件,相应的下载次数加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; 

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

<div id="demo"> 
  <ul class="filelist"> 
  </ul> 
</div> 

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;} 

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); 
} 

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 '文件不存在!'; 
} 

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 
  }); 
}); 

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

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software