PHP: Get maximum upload filesize

When handling file uploads its handy to check beforehand if the file fits insides the restrictions PHP sets in its ini file. To determine these the following functions are really handy:

function getShortInBytes($val) {
	$val = trim($val);
	$last = strtolower($val[strlen($val) - 1]);
	switch ($last) {
		case 'g':
			$val *= 1024;
		case 'm':
			$val *= 1024;
		case 'k':
			$val *= 1024;
	}
	return $val;
}

function getMaxFilesize() {
	$maxUpload = getShortInBytes(ini_get('upload_max_filesize'));
	$maxPost = getShortInBytes(ini_get('post_max_size'));
	if($maxPost<=$maxUpload){
		return $maxPost;
	}
	return $maxUpload;
}

With these you get the smallest possible filesize you can upload to the server. Make sure to also check the size when submitting:

$(function() {
    $('#videoFile').change(function() {
        if (this.files[0].size >= maxFileSize) {
            $(this).parents('.form-group').addClass('has-error').removeClass('has-success');
        }else{
            $(this).parents('.form-group').addClass('has-success').removeClass('has-error');
        }
    });

    //Prevent submission when not a valid file
    $('#submitCheck').on('submit', function(e) {
        if ($(this).find('.has-error').size() > 0) {
            e.preventDefault();
        }
    })
});

 

Published by

Kordian Bruck

I'm a TUM Computer Science Alumni. Pizza enthusiast. Passionate for SRE, beautiful Code and Club Mate. Currently working as an SRE at Google. Opinions and statements in this blog post are my own.

Leave a Reply