PHP+Mysql統計文件下載次數實例,實現的原理也很簡單,是通過前台點擊鏈接download.php傳參id,來更新點擊次數。
獲取文件列表:
<?php require 'conn.php'; $query = mysql_query("SELECT * FROM downloads"); $lists = array(); while ($row = mysql_fetch_assoc($query)) { $lists[] = $row; } ?>
讀取文件列表,並加上download.php鏈接和參數id:
<ul class="filelist"> <?php foreach ($lists as $v) { ?> <li><a href="download.php?id=<?php echo $v['id'] ?>"><?php echo $v['filename'] ?><span class="downcount" title="下載次數"><?php echo $v['downloads'] ?></span><span class="download">點擊下載</span></a></li> <?php } ?> </ul>
點擊下載按鈕,累加文件次數:
$(function() { $('ul.filelist a').live('click', function() { var count = $('.downcount', this); count.text(parseInt(count.text()) + 1); }); });
download.php文件源碼:
<?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 = 'files/' . $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 '文件不存在!'; } ?>
本文轉自:https://www.sucaihuo.com/php/224.html 轉載請注明出處!