File size limit
Learn to check the file size limit for an upload.
File size limit
Accepting unlimited sizes can fill the server's disk. So you should set an upper limit for file size. For a profile picture, 2 MB (2097152 bytes) is a reasonable limit.
The uploaded file's size is stored in $_FILES['avatar']['size'] in bytes. The check is simple: if ($file['size'] > $maxBytes).
This limit cannot exceed upload_max_filesize (php.ini); PHP already rejects files above that. You can keep your own app limit lower.
The upload_max_filesize limit
PHP itself also sets limits through two config values: upload_max_filesize is the max size of a single file, post_max_size is the max size of the whole POST body. These live in php.ini.
If a file exceeds upload_max_filesize, PHP cancels the upload and sets $_FILES['avatar']['error'] to UPLOAD_ERR_INI_SIZE (1). The size field becomes 0.
So your own check is for the app limit; PHP's limit already applies. Using both together is safest.
Exercise The checkSize function
Write a checkSize(array $file, int $maxBytes): string function. Inside it, check with if ($file['size'] > $maxBytes). If over, return 'Too large: ' . $file['size'] . ' > ' . $maxBytes; otherwise return 'Accepted: ' . $file['size'] . ' bytes'. For testing, define $_FILES['avatar'] (name: 'profile.jpg', tmp_name: '/tmp/phpAbCd.tmp', error: 0, size: 5242880) and write echo checkSize($_FILES['avatar'], 2097152) . "\n".
Show example solution
' + size + ' > ' + maxBytes; else 'Accepted: ' + size + ' bytes'.
Example solution:
<?php
// Check file size
function checkSize(array $file, int $maxBytes): string {
if ($file['size'] > $maxBytes) {
return "Too large: " . $file['size'] . " > " . $maxBytes;
}
return "Accepted: " . $file['size'] . " bytes";
}
$_FILES['avatar'] = [
'name' => 'profile.jpg',
'tmp_name' => '/tmp/phpAbCd.tmp',
'error' => 0,
'size' => 5242880
];
echo checkSize($_FILES['avatar'], 2097152) . "\n";
Test yourself
-
Where is the uploaded file size stored?
- $_SERVER['CONTENT_LENGTH']
- $_POST['size']
- $_FILES['file']['error']
- $_FILES['file']['size']
Show answer
$_FILES['file']['size'] — Correct. The size field gives the size in bytes.
-
Size comparison
if ($file['size'] > ____) { return false; }Show answer
if ($file['size'] > $maxBytes) { return false; } -
Match size units
- 1 KB
- 1024 bytes
- 1 MB
- 1048576 bytes
- 2 MB
- 2097152 bytes
- 5 MB
- 5242880 bytes