Streaming files from the Internet through PHP is slow

I am writing a script that will transfer a file from a web address through my server to a user. In the current state, it works, but it is very slow.

Here is the relevant code:

/* Bytes per second */
define('TRANSFER_CAP', 1048576);

/* Hard part... stream the file to the user */
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $filename);
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $filesize);

$file = fopen($fileLocation, 'rb');
if(!$file) {
    // TODO: handle errors
}

while(!feof($file)) {
    echo fread($file, TRANSFER_CAP / 2);
    ob_flush();
    flush();

    /* Limit the download speed by sleeping */
    usleep(500);
}

This script works on my local machine. When I request a file in my browser (without going through the script), I get a solid download speed of about 2.5 MB / s, which is my maximum speed on the network. However, if I run the script and try to download the same file, I get only 240-250 KB / s.

I know this is not a script limiting the transfer rate because I set it to 1 MB / s. I also can't think of anything in this script that creates a lot of overhead that slows down the speed.

: - , readfile(), :

readfile('http://cachefly.cachefly.net/100mb.test');

fopen fread?

+5
2

HTTP- ? , PHP , , , .

0

All Articles