Search code examples
phpvalidationgetimagesize

getimagesize() limiting file size for remote URL


I could use getimagesize() to validate an image, but the problem is what if the mischievous user puts a link to a 10GB random file then it would whack my production server's bandwidth. How do I limit the filesize getimagesize() is getting? (eg. 5MB max image size)

PS: I did research before asking.


Solution

  • You can download the file separately, imposing a maximum size you wish to download:

    function mygetimagesize($url, $max_size = -1)
    {
            // create temporary file to store data from $url
            if (false === ($tmpfname = tempnam(sys_get_temp_dir(), uniqid('mgis')))) {
                    return false;
            }
            // open input and output
            if (false === ($in = fopen($url, 'rb')) || false === ($out = fopen($tmpfname, 'wb'))) {
                    unlink($tmpfname);
                    return false;
            }
            // copy at most $max_size bytes
            stream_copy_to_stream($in, $out, $max_size);
    
            // close input and output file
            fclose($in); fclose($out);
    
            // retrieve image information
            $info = getimagesize($tmpfname);
    
            // get rid of temporary file
            unlink($tmpfname);
    
            return $info;
    }