<?php
// connect to database (this uses PHP5's MySQLi Class)
$db = new mysqli('localhost', 'username', 'password', 'database');
if ($db->connect_error)
{
die("Connect Error ({$db->connect_errno}) {$db->connect_error}");
}
// filter_* is PHP 5 only
$fileid = filter_input(INPUT_GET, 'fileid', FILTER_SANITIZE_NUMBER_INT);
if ($fileid > 0)
{
/**
Let's say your database is setup this way:
CREATE TABLE `mp3s` (
`fileid` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`filename` VARCHAR(255) NOT NULL,
`downloads` INT UNSIGNED NOT NULL
);
*/
$fsql = $db->query("
SELECT filename
FROM mp3s
WHERE fileid = $fileid
");
if ($fsql->num_rows() > 0)
{
$filename = $fsql->fetch_array();
$filename = "./mp3s/{$filename['filename']}";
$filesize = @filesize($filename);
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/force-download; name=\"" . basename($filename) . "\";");
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: $filesize");
// 20971520 = 20MB, could always adjust this - has to be in BYTES, not kilobytes
if ($filesize >= 20971520)
{
$fp = @fopen($filename, 'rb');
while (!feof($fp))
{
echo fread($fp, 2048);
}
unset($fp);
}
else
{
@readfile($filename);
}
$db->query("UPDATE mp3s SET downloads = downloads + 1 WHERE fileid = $fileid LIMIT 1");
exit;
}
$fsql->close();
}
$db->close();
?>