Ok as you have most of the code missing here is an example, basically your need to call the counter code inside the download.php
file, and pass through the file contents after doing the counter code and setting download headers. also be wary or allowing malicious people to download any file from your server by just passing the file name to the download function. download.php?file=index.php
ect
<?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></title>
</head>
<body>
<a href="./download.php?file=exampleA.zip">exampleA.zip</a> (Downloaded <?php echo get_download_count('exampleA.zip');?> times)<br>
<a href="./download.php?file=exampleB.zip">exampleB.zip</a> (Downloaded <?php echo get_download_count('exampleB.zip');?> times)<br>
</body>
</html>
download.php as you can see it outputs no HTML as this would corrupt the file.
<?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"));
}
?>
Make sure you check the $downloads_folder
variable is correct. Hope it helps.
Download Full example code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…