PHP – Obtain the maximum allowed file upload size

PHP – Obtain the maximum allowed file upload size

This was actually remarkably difficult to do, in terms of the volume of code required. It uses the fact that there are 3 things which affect the size of a file which can be uploaded: upload_max_filesize, post_max_size and memory_limit. The below code is useful for providing the user with the upload limit on a file upload form.

The code also uses the PHP quirk feature whereby casting a string, which starts with digits, to int will return the int value of the first digits – e.g. (int)’123abc321′ evaluates to 123.

This may, however, be a ridiculous way to do it  and an easier way may exist. Feel free to comment if you know one.

  1. function max_upload_size() {
  2. // Multipliers to make byte values from php.ini shorthand
  3. $suffix_multipliers = array(
  4. 'K'=>1024,
  5. 'M'=>1024*1024,
  6. 'G'=>1024*1024*1024
  7. );
  8.  
  9. // Values to consider
  10. $vals = array(
  11. 'upload' => ini_get('upload_max_filesize'),
  12. 'post' => ini_get('post_max_size'),
  13. 'mem' => ini_get('memory_limit')
  14. );
  15.  
  16. // Convert above values to bytes based on their shorthand notation
  17. $byte_vals = array();
  18.  
  19. foreach ($vals as $name=>$val) {
  20. if ($suffix = preg_match('/[a-z]+$/i', $val, $matches)) {
  21. // "10M" cast to int is 10
  22. if (isset($suffix_multipliers[$matches[0]])) {
  23. $byte_vals[$name] = (int)$val * $suffix_multipliers[$matches[0]];
  24. }
  25. else {
  26. $byte_vals[$name] = (int)$val;
  27. }
  28. }
  29. }
  30.  
  31. // Get the key(s) of the smallest entries
  32. $smallest_keys = array_keys($byte_vals, min($byte_vals));
  33. // Get one of these
  34. $smallest_key = reset($smallest_keys);
  35.  
  36. // Return the smallest
  37. return $vals[$smallest_key];
  38. }

One comment

  1. From Twitter: just wanted to say that I’m enjoying reading the articles on your blog. Keep it up!

Leave a Reply

Your email address will not be published. Required fields are marked *