- PHP File Upload
- Configure The «php.ini» File
- Create The HTML Form
- Create The Upload File PHP Script
- Check if File Already Exists
- Limit File Size
- Limit File Type
- Complete Upload File PHP Script
- Complete PHP Filesystem Reference
- How to Change the Timeout on the Modern File Upload
- Setup
- Установка лимитов PHP на обработку данных из форм
- Описание директив
- post_max_size
- Пример в htaccess:
- upload_max_filesize
- Пример:
- max_input_vars
- Пример:
- max_execution_time
- Пример:
- max_input_time
- Пример:
- memory_limit
- Пример:
- Установка директив в .htaccess
- Установка директив в PHP-скрипте
- Получение значений в PHP-скрипте
- Получение значения upload_max_filesize в PHP:
- Результат:
- Возможные ошибки
PHP File Upload
However, with ease comes danger, so always be careful when allowing file uploads!
Configure The «php.ini» File
First, ensure that PHP is configured to allow file uploads.
In your «php.ini» file, search for the file_uploads directive, and set it to On:
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
Some rules to follow for the HTML form above:
- Make sure that the form uses method=»post»
- The form also needs the following attribute: enctype=»multipart/form-data». It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
- The type=»file» attribute of the tag shows the input field as a file-select control, with a «Browse» button next to the input control
The form above sends data to a file called «upload.php», which we will create next.
Create The Upload File PHP Script
The «upload.php» file contains the code for uploading a file:
$target_dir = «uploads/»;
$target_file = $target_dir . basename($_FILES[«fileToUpload»][«name»]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST[«submit»])) $check = getimagesize($_FILES[«fileToUpload»][«tmp_name»]);
if($check !== false) echo «File is an image — » . $check[«mime»] . «.»;
$uploadOk = 1;
> else echo «File is not an image.»;
$uploadOk = 0;
>
>
?>?php
- $target_dir = «uploads/» — specifies the directory where the file is going to be placed
- $target_file specifies the path of the file to be uploaded
- $uploadOk=1 is not used yet (will be used later)
- $imageFileType holds the file extension of the file (in lower case)
- Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called «uploads» in the directory where «upload.php» file resides. The uploaded files will be saved there.
Check if File Already Exists
Now we can add some restrictions.
First, we will check if the file already exists in the «uploads» folder. If it does, an error message is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) echo «Sorry, file already exists.»;
$uploadOk = 0;
>
Limit File Size
The file input field in our HTML form above is named «fileToUpload».
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0:
// Check file size
if ($_FILES[«fileToUpload»][«size»] > 500000) echo «Sorry, your file is too large.»;
$uploadOk = 0;
>
Limit File Type
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:
Complete Upload File PHP Script
The complete «upload.php» file now looks like this:
$target_dir = «uploads/»;
$target_file = $target_dir . basename($_FILES[«fileToUpload»][«name»]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
?php
// Check if image file is a actual image or fake image
if(isset($_POST[«submit»])) $check = getimagesize($_FILES[«fileToUpload»][«tmp_name»]);
if($check !== false) echo «File is an image — » . $check[«mime»] . «.»;
$uploadOk = 1;
> else echo «File is not an image.»;
$uploadOk = 0;
>
>
// Check if file already exists
if (file_exists($target_file)) echo «Sorry, file already exists.»;
$uploadOk = 0;
>
// Check file size
if ($_FILES[«fileToUpload»][«size»] > 500000) echo «Sorry, your file is too large.»;
$uploadOk = 0;
>
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) echo «Sorry, your file was not uploaded.»;
// if everything is ok, try to upload file
> else if (move_uploaded_file($_FILES[«fileToUpload»][«tmp_name»], $target_file)) echo «The file «. htmlspecialchars( basename( $_FILES[«fileToUpload»][«name»])). » has been uploaded.»;
> else echo «Sorry, there was an error uploading your file.»;
>
>
?>
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.
How to Change the Timeout on the Modern File Upload
Would you like to change the timeout when uploading files through the Modern File Upload form field? This can be particularly helpful when you are expecting large files to be uploaded through your form.
By default, the timeout set on the Modern File Upload field is set to 30 seconds or 30000 milliseconds, with a small PHP snippet you can easily change this timeout to be whatever you’d like.
Setup
All you need to do is add this snippet to your site.
If you’re not sure where or how to add snippets to your site, please take a look at this tutorial.
In our example, we’re changing the timeout from 30000 milliseconds (30 seconds) to 60000 milliseconds (60 seconds).
/** * Change the timeout on the modern file upload from 30 to 60 seconds. * * @link https://wpforms.com/developers/how-to-change-the-timeout-on-the-modern-file-upload/ */ function wpf_dev_modern_file_upload_timeout() < ?> add_action( 'wpforms_wp_footer', 'wpf_dev_modern_file_upload_timeout', 30 );
You’ll just need to set the 60000 to what you would like.
Please note that just changing this number, doesn’t mean that your hosting company won’t also have a global cap set on your timeout functions, also known as PHP max_execution_time . You’ll need to reach out to your hosting company to increase this on your server if you have the need to increase this amount as well.
And that’s it! You’ve successfully increased the timeout from 30 seconds (30000 milliseconds) to 60 seconds (60000 milliseconds). Would you like to also track successful form submissions with Google Analytics without the need for a plugin? Check out this snippet on How to Track Form Submissions Using Google Analytics 4.
Установка лимитов PHP на обработку данных из форм
Перечень настроек PHP, которые могут ограничить отправку форм и файлов через POST-запрос.
Описание директив
post_max_size
Устанавливает максимальный размер данных, отправленных методом POST, включая размер загружаемых файлов, по умолчанию 8Mb .
- Для загрузки больших файлов это значение должно быть больше значения upload_max_filesize.
- Значение можно указать числом в байтах, K (в килобайтах), M (в мегабайтах) и G (в гигабайтах).
- Значение «0» снимает ограничение только в версиях PHP 5.3.2 и 5.2.12.
Пример в htaccess:
php_value post_max_size 100M
upload_max_filesize
Максимальный размер загружаемых файлов на сервер. По умолчанию 2Mb.
Пример:
php_value upload_max_filesize 100M
max_input_vars
Максимальное количество переменных, которое может быть принято в одном запросе. По умолчанию 1000.
Если данный лимит будет превышен, то после отправки формы массив $_GET или $_POST будет пустым.
Пример:
php_value max_input_vars 2000
max_execution_time
Директива задаёт максимальное время в секундах, в течение которого скрипт должен полностью загрузиться. Если этого не происходит, работа скрипта завершается. По умолчанию на загрузку даётся 30 секунд.
Значение «0» снимает ограничение на время выполнения.
Пример:
php_value max_execution_time 600
Также, максимальное время выполнения скрипта задает функция set_time_limit($seconds) .
max_input_time
Задаёт максимальное время в секундах, в течение которого скрипт должен разобрать все входные POST или GET данные. Это время измеряется от момента, когда PHP вызван на сервере до момента, когда скрипт начинает выполняться.
- Значение по умолчанию «-1» – будет использоваться max_execution_time.
- Значение «0» – без ограничений по времени.
Пример:
php_value max_input_time 600
memory_limit
Задаёт максимальный объем памяти в байтах, который разрешается использовать скрипту. По умолчанию 128Mb.
Пример:
php_value memory_limit 200M
Установка директив в .htaccess
# Максимальный размер данных php_value post_max_size 110M # Максимальный размер файлов php_value upload_max_filesize 100M # Максимальное количество переменных php_value max_input_vars 2000 # Максимальное время выполнения скрипта php_value max_execution_time 600 # Максимальное время обработки данных php_value max_input_time 600 # Память для скрипта php_value memory_limit 200M
Установка директив в PHP-скрипте
ini_set('post_max_size', '110M'); // Максимальный размер данных ini_set('upload_max_filesize', '100M'); // Максимальный размер файлов ini_set('max_input_vars', '2000'); // Максимальное количество переменных ini_set('max_execution_time', '600'); // Максимальное время выполнения скрипта ini_set('max_input_time', '600'); // Максимальное время обработки данных ini_set('memory_limit', '200M'); // Память для скрипта
Получение значений в PHP-скрипте
Действующие значения настроек PHP можно посмотреть с помощью функции phpinfo() или получить значение параметра настройки с помощью функции ini_get($option) .
Получение значения upload_max_filesize в PHP:
'; echo 'Максимальный размер файлов: ' . ini_get('upload_max_filesize') . '
'; echo 'Максимальное количество переменных: ' . ini_get('max_input_vars') . '
'; echo 'Максимальное время выполнения скрипта: ' . ini_get('max_execution_time') . '
'; echo 'Максимальное время обработки данных: ' . ini_get('max_input_time') . '
'; echo 'Память для скрипта: ' . ini_get('memory_limit') . '
';
Результат:
Максимальный размер данных: 128M Максимальный размер файлов: 128M Максимальное количество переменных: 10000 Максимальное время выполнения скрипта: 300 Максимальное время обработки данных: -1 Память для скрипта: 1024M
Возможные ошибки
После отправки формы с множеством полей, массив $_POST пустой.
– В форме количество полей превышает значение max_input_vars.
Ошибка «Fatal error: Allowed memory size»
– Скрипт превысил значение параметра PHP memory_limit.
Ошибка «504 Gateway Time Out»
– Скрипт выполняется слишком долго, нужно увеличить значение max_execution_time. Как правило после вывода этой ошибки в браузере, скрипт будет еще какое-то время работать.