root22
Coder
Hi there. I found a php file download counter script on google but can't seem to get it working on the page where I want it. I also do not understand php and am a bit rusty at Html and Css. I created a table and just typed random numbers for the downloads column but would like the script to count the downloads instead. Does anyone know how I can get this working? Thanks. Here's the link to the table where I need the counter to work with.
And heres the index.php
and here is the download.php
And heres the index.php
PHP:
<?php
function get_download_count($file=null){
$counters = './counters/';
if($file == null) return 0;
$count = 0;
if(file_exists($counters.md5($file).'_counter.txt')){
$fp = fopen($counters.md5($file).'_counter.txt', "r");
$count = fread($fp, 1024);
fclose($fp);
}else{
$fp = fopen($counters.md5($file).'_counter.txt', "w+");
fwrite($fp, $count);
fclose($fp);
}
return $count;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Downloads</title>
</head>
<body>
<li><a href="./download.php?file=exampleA.zip">exampleA.zip</a> (Downloaded <?php echo get_download_count('exampleA.zip');?> times)</li>
<li><a href="./download.php?file=exampleB.zip">exampleB.zip</a> (Downloaded <?php echo get_download_count('exampleB.zip');?> times)</li>
</body>
</html>
and here is the download.php
PHP:
<?php
//where the files are
$downloads_folder = './files/';
$counters_folder = './counters/';
//has a file name been passed?
if(!empty($_GET['file'])){
//protect from people getting other files
$file = basename($_GET['file']);
//does the file exist?
if(file_exists($downloads_folder.$file)){
//update counter - add if dont exist
if(file_exists($counters_folder.md5($file).'_counter.txt')){
$fp = fopen($counters_folder.md5($file).'_counter.txt', "r");
$count = fread($fp, 1024);
fclose($fp);
$fp = fopen($counters_folder.md5($file).'_counter.txt', "w");
fwrite($fp, $count + 1);
fclose($fp);
}else{
$fp = fopen($counters_folder.md5($file).'_counter.txt', "w+");
fwrite($fp, 1);
fclose($fp);
}
//set force download headers
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file.'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($downloads_folder.$file)));
//open and output file contents
$fh = fopen($downloads_folder.$file, "rb");
while (!feof($fh)) {
echo fgets($fh);
flush();
}
fclose($fh);
exit;
}else{
header("HTTP/1.0 404 Not Found");
exit('File not found!');
}
}else{
exit(header("Location: ./index.php"));
}
?>