A
A
Anton2021-11-18 13:43:33
AJAX
Anton, 2021-11-18 13:43:33

Image size error output via php, if the image size is more than 5 megabytes, how to check?

Through js + ajax, I check the fields for fullness in the form and display an error with php in validation.

Example, this is how I check if a photo is selected or not:

if (empty($_FILES['images']['name'][0])) {
throw new Exception('Выберите фото вид спереди.');
}


And how can I check the size of the photo, let's say if it is more than 5 megabytes and display the text, they say the photo weighs too much.

I tried to stir up even, but this example did not fit.
$app_config_max_size = 1000000;
$max_size = $app_config_max_size;
if ($_FILES['images']['name'][0]['size'] > $max_size) {
throw new Exception('limit exceeded');
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
grek_cheburek, 2021-11-19
@grek_cheburek

Never trust what the user sends you. I know that $_FILES can be changed.
There is a function in php, filesize()
Use it to check something like that.

<?php
$max_size  = 1024*1024*5; // Один килобайт имеет 1024 байт. Их умножаем и получаем мегабайт. Далее умножаем на пять.
$tmp_size = filesize($_FILES['file_img']['tmp_name'][0]);
if ($tmp_size>$max_size) {
 echo "Ошибка, ваш файл привышает 5 мб"; exit();
}
?>

Something like this. And one moment. If you allow other users to upload pictures to the site, then this is not the last check with the file size. You also need to check if the picture is harmful.

A
Anton, 2021-11-18
Websaytovsky @ws17

I'm sorry, I found a solution:

$maxFileSize = 5 * 10e6; // = 5 000 000 bytes = 5MB
        if ($_FILES['images']['size'][0] > $maxFileSize) {
          throw new Exception('Максимальный размер изображения не должен превышать 5 мегабайт, ваша фотография вести больше 5 мегабайт.');
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question