Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Number of times downloaded

How can I display a counter that counts the number of times a file is downloaded? I've seen it before. "Downloaded 450 times". Thanks.

like image 698
user Avatar asked Nov 20 '25 02:11

user


1 Answers

Don't let the user download a file directly, but through a script like the following ...

$file = $_REQUEST['file'];
$dldir = "downloads/";

if (
  (file_exists($dldir.$file) &&      // file exists
  (strpos($file, "../") === false))  // prevent an attacker from switching to a parent directory
) {

   header('Content-type: '.mime_content_type($dldir.file));
   header("Content-Transfer-Encoding: binary");
   header("Content-Length: " . filesize($dldir.$file) ."; "); 
   header('Content-Disposition: attachment; filename="'.$file.'"');

   echo file_get_contents($dldir.$file);

/** Update the counter here, e.g. by using mysql **/
} else {
   die("File not found");
}
like image 150
ty812 Avatar answered Nov 22 '25 17:11

ty812



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!