prasad chinthala prasad chinthala - 16 days ago 5
PHP Question

how to check uploaded file size smaller than or equals to 20 kb limit?

Our application has a requirement that all the uploaded files should be below or equals to 20 KB limit. I am unable to calculate the filesize in PHP as I don't know how it calculates filesize for each 1KB.

I am thinking that 1 KB equals to 1024 bytes so 20 KB is equals to 20*1024 = 20480. Is this correct? My code is accepting files larger than 20KB.

function my_method_name() {

if ( isset( $_POST['submit-button-name'] ) && !empty( $_FILES ) ) {
if($_FILES['file_name']['size'] == 0) {
return 1;
}
else {
$path = /Path/to/dir;
$allowed = array('gif','GIF','png','PNG','jpg','JPG','JPEG','jpeg');
$filename = $_FILES['file_name']['name'];
$filesize = $_FILES['file_name']['size'];
$ext = pathinfo($filename,PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) && $filesize > 20480) {
return 0;
}
else {
$id = media_handle_upload('file_name', 1199); //post id of Client Files page
return $id;
}
}
}
}

Answer

Your condition for returning 0 is

!in_array($ext,$allowed) && $filesize > 20480

In order for it to be true, both conditions must be true. That is, only files with a size greater than 20480 and with an extension that isn't allowed will cause the first branch to be followed.

Switch && to ||.

Alternatively, it is usually clearer to put the "positive" path first in if / else blocks. You could do

if (in_array($ext, $allowed) && $filesize <= (20 * 1024)) {
    // Logic to handle accepted download
} else {
    // Logic to handle rejected download
}
Comments