arijulianto

PHP Script Download Counter

May 1st, 2014
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.63 KB | None | 0 0
  1. <?php
  2.     //connect database
  3.     mysql_connect("localhost", "username", "password");
  4.     mysql_select_db("dbname");
  5.  
  6.     $filename = mysql_real_escape_string($_GET['file']);
  7.     $path = "download-files/";
  8.     $fullPath = $path.$filename;
  9.    
  10.     $filetypes = array("rar","zip","pdf","doc","docx","Xls","xlsx","ppt","pptx","txt"); // daftar ekstensi file yang support
  11.     $ext = end(explode('.', $filename);
  12.    
  13.     if (!in_array($ext, $filetypes)) {
  14.         echo "Invalid download type.";
  15.         exit;
  16.     }
  17.  
  18.     if ($fd = fopen ($fullPath, "r")) {
  19.         //add download stat
  20.         $result = mysql_query("SELECT COUNT(*) AS countfile FROM download WHERE filename='" . $filename . "'");
  21.         $data = mysql_fetch_array($result);
  22.         $q = "";
  23.    
  24.         if ($data['countfile'] > 0) {
  25.             $q = "UPDATE download SET stats = stats + 1 WHERE
  26.            filename = '" . $filename . "'";
  27.         } else {
  28.             $q = "INSERT INTO download (filename, stats) VALUES
  29.            ('" . $filename . "', 1)";
  30.         }
  31.        
  32.         $statresult = mysql_query($q);
  33.        
  34.         //the next part outputs the file
  35.         $fsize = filesize($fullPath);
  36.         $path_parts = pathinfo($fullPath);
  37.        
  38.         header("Content-type: application/octet-stream");
  39.         header("Content-Disposition: filename=".$path_parts["basename"]."");
  40.         header("Content-length: $fsize");
  41.         header("Cache-control: private"); //use this to open files directly
  42.         while(!feof($fd)) {
  43.             $buffer = fread($fd, 2048);
  44.             echo $buffer;
  45.         }
  46.     }
  47.     fclose ($fd);
  48.     exit;
  49.  
  50. ?>
Add Comment
Please, Sign In to add comment