I am looking to limit download speed of a file, I have found the below thread on here which works wonders for locally stored files, however my files are stored on an external server and I'm not entirely sure how to make this work with said server.
Reference: Limit download speed using PHP
Code:
<?php
set_time_limit(0);
// local file that should be send to the client
$local_file = 'https://remoteserver.com/example.mp4';
// filename that the user gets as default
$download_file = 'https://remoteserver.com/example.mp4';
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 1024;
if(file_exists($local_file) && is_file($local_file)) {
// send headers
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);
// flush content
flush();
// open file stream
$file = fopen($local_file, "r");
while(!feof($file)) {
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
flush();
// sleep one second
sleep(1);
}
// close file stream
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}
if ($dl) {
} else {
header('HTTP/1.0 503 Service Unavailable');
die('Abort, you reached your download limit for this file.');
}
?>
Both servers share the same base domain, just different subdomains. I could limit download speed using httpd configuration on the remote server, however I am looking to make different speeds for different user permissions and this would just result in an overall limitation.
My Solution:
I have used httpd / apache2 config to limit download speeds to a specified URL for example https://remoteserver.com/slow/...
and https://remoteserver.com/fast/...
using the below.
<Location "/slow">
SetOutputFilter RATE_LIMIT
SetEnv rate-limit 5120
SetEnv rate-initial-burst 5120
</Location>
<Location "/fast">
SetOutputFilter RATE_LIMIT
SetEnv rate-limit 204800
SetEnv rate-initial-burst 204800
</Location>
I then used .htaccess write to include that part of the URL for me as my file structure already existed and couldn't be split into subfolders.
RewriteEngine On
RewriteRule ^/?(?:slow|fast)(/downloads/.+)$ $1 [L,NC]