download.phps

<?
/*
This script limits the download speed of files, for example when streaming music or videos.
Usage example for .htaccess:
RewriteEngine on
RewriteRule ^flam/mp3/(.*)$ download.php?file=$1
This would limit the speed of all the files in the directory /flam/mp3/ on the server.
*/
$speed = 29; // speed limit in KB/s
$bandwidth_limit = true;
$dir = '/var/www/flam/mp3/';
$file_dl = $_GET['file'];
if (substr(realpath($dir.$file_dl), 0, strlen($dir)) !== $dir || !($fn = @fopen($dir.$file_dl, 'rb')))
{
    die($html_heading.'<h3>Error 401: permission denied</h3> you cannot access <em>'.htmlentities($file_dl).'</em> on this server.');
}
$outname = get_basename($file_dl);
$size = @filesize($dir.$file_dl);
if ($size !== false)
{
    header('Content-Length: '.$size);
}
header('Content-Disposition: attachment; filename="'.$outname.'"');
@set_time_limit(0);
while (true)
{
    $temp = @fread($fn, (int)($speed * 1024));
    if ($temp === '')
    {
        break;
    }
    echo $temp;
    flush();
    if ($bandwidth_limit)
    {
        sleep(1);
    }
}
fclose($fn);
die();

function get_basename($fn)
//returns everything after the slash, or the original string if there is no slash
{
    return basename(str_replace('\\', '/', $fn));
}

?>