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 '文件不存在!'; } ?>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!