Logo

[php] Codeschnipsel: Simpler Downloadcounter

Ein einfacher Downloadzähler, ermöglicht Download beliebiger Dateitypen und beliebige Dateianzahl.

Ordnerstruktur:
/downloads/ → enthält Dateien
/download.php → Downloadcounter
/downloads.php→ speichert Daten (chmod 666)
/test.php → Beispiel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
download.php:
<?php
// keine Datei ausgewählt
if(!isset($_GET['file']))
    exit(
"no file chosen");
// Datei existiert nicht
if(!file_exists("downloads/".$_GET['file']))
    exit(
"file does not exist");
include(
"downloads.php");
// Zähler anlegen bzw. erhöhen
if(!array_key_exists($_GET['file'], $downloads))
    
$downloads[$_GET['file']] = 1;
else
    
$downloads[$_GET['file']]++;
// Daten speichern
$input "<?php\n";
$input .= "\$downloads = ".var_export($downloadstrue).";\n";
$input .= "?>";
$handle fopen("downloads.php""w");
fwrite($handle$input);
fclose($handle);
// Datei als Download öffnen
$file "downloads/".$_GET['file'];
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private"false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$_GET['file']."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
ob_clean();
flush();
readfile($file);
?>

test.php:
<?php include("downloads.php"); ?>
<a href="download.php?file=test.txt">Download</a>
<?php echo $downloads['test.txt'?> Downloads