Search code examples
phpimagecachingbandwidthbandwidth-throttling

PHP giving image with throttled bandwitdth and caching?


Here is a link to an example bandwidth throttling PHP script for a file. I see an improvement I can make that's unrelated that I'll make myself later, but other than that... How could you use this script to make another script that returns an image with throttled bandwidth, but caches the images forever? The image will never change.


Solution

  • I think all you were asking was to modify that script to work with an image and cache the content. This should do it, pending any minor errors I may have:

    <?php
    
    $file = "yourimage.jpg"; // file to be send to the client
    $speed = 8.5; // 8,5 kb/s download rate limit
    
    // if $file is coming from get, I would use this to prevent against a nullbyte attack:
    $file = str_replace(chr(0), '', $file);
    
    if (file_exists($file) && is_file($file)) {
        header("Expires: ".gmdate('D, d M Y H:i:s', time()+3600*24*3000).'GMT'); // expires in 3000 days. 
        header("Pragma: cache");
        header("Content-Type: image/jpeg"); // needs to be changed for the file type.
        header("Content-Length: ".filesize($file));
        header("Cache-Control: max-age=" . 3600*24*3000);
    
        flush();
    
        $fd = fopen($file, "r");
        while(!feof($fd)) {
             echo fread($fd, round($speed*1024));
            flush();
            sleep(1);
        }
        fclose ($fd);
    
    }