檔案下載統計php程式設計 (轉)

worldblog發表於2007-12-02
檔案下載統計php程式設計 (轉)[@more@]現在有許多站點都提供了統計功能,本文討論的是如何使用實現此功能,對於想隱藏下載檔案路徑,避免直接使用url下載的者,本文也具有一定的參考價值。:namespace prefix = o ns = "urn:schemas--com::office" />

實現環境:++Php+My

98+PWS4+Php+

一、結構

資料庫中建立一個表,檔案資訊,包括檔案編碼、名稱、下載路徑、統計,相應的sql檔案內容如下:

CREATE DATABASE dl_;

CREATE TABLE dl_file (

  id varchar(6),

  name varchar(50),

  url varchar(200),

  count bigint(10)

);

INSERT INTO dl_file VALUES( '000001', 'test', 'test.zip', 0);

INSERT INTO dl_file VALUES( '000002', 'tif', '/123.tif', 0);

二、php程式設計

1、  檔案

函式檔案包括資料庫連線初始化函式和提示資訊顯示函式。

dl_func.php3:

  //初始化資料庫連線的

function dl_dbconnect(){

    error_reporting(1+4);  //禁掉warning性錯誤

    $dl_in=0;

    $dl_in=mysql_connect("localhost:3306","","123456");

    if(!dl_in) { //如果連線失敗,退出

      echo "資料庫無法連線";

      exit;

    }

    mysql__db("dl_db",$dl_in);

    return $dl_in;

  }

 

  //顯示提示資訊的函式

  function infopage($strInfo){

    echo "

  }

?>

 

2、  下載連線頁面

下載連線頁面從資料庫讀取下載檔案資訊並顯示。

filelist.php3:

檔案下載

function newopen(url){

  window.open(url,"_self");

  return;

}

require("dl_func.php3");

$dl_in=dl_dbconnect();

$strQuery="select * from dl_file order by id";

$dl_res=mysql_query($strQuery,$dl_in);

while($arr_dlfile=mysql_fetch_array($dl_res)){

  echo "";

  echo "$arr_dlfile[name]";

  echo " ";

  echo "(下載次數:$arr_dlfile[count])";

  echo "
";

}

mysql_close($dl_in);

?>

3、  下載頁面

當檔案存在時,下載頁面轉到要下載的檔案,如果發生錯誤,則顯示提示資訊。

filedown.php3:

  require("dl_func.php3");

  $dl_in=dl_dbconnect();

  $strQuery="select url from dl_file where id='$id'";

  $dl_res=mysql_query($strQuery,$dl_in);

  if(!($arrfile=mysql_fetch_array($dl_res))){ //選擇結果為空

    infopage("錯誤的id號");

    exit;

  }else{

    $arr_temp=split("/",$arrfile[url]);

    $filename=$arr_temp[sizeof($arr_temp)-1];

    if(strlen(trim($filename))==0){//檔名稱為空

      infopage("錯誤的檔案");

      exit;

    }else{

      $strQuery="update dl_file set count=count+1 where id='$id'";

      mysql_query($strQuery,$dl_in);

      header("Content-type: application/file");

      header("Content-Disposition: attachment; filename=$filename");//預設時檔案儲存對話方塊中的檔名稱

      header("location:$arrfile[url]");

    //echo “this is test for echo-download”;

    }

  }

  mysql_close($dl_in);

?>

實現的原理是filelist.php3顯示所有檔案的連線,然後根據傳遞的id來得到檔案的名稱和路徑,透過重新定位來下載檔案。以上程式筆者測試過,執行正常。

檔案url可以是本地的,也可以是其他上的。

如果檔案內容儲存在資料庫中,或者檔案沒有在http和的路徑下,解決的方法可以利用將檔案的內容echo出來取代header(“location:$arrfile[url]”),由於讀取檔案方法相對簡單,這裡不再贅述。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-987255/,如需轉載,請註明出處,否則將追究法律責任。

相關文章