Php files size type

PHP Get File Type, Size, Extension Before Upload

To get file type, size and extension before upload in PHP; In this tutorial, you will learn how to get the file type, size, and extension before uploading it using PHP.

When building a file upload feature on a web application, it is essential to validate and retrieve the file type, size, and extension before uploading it. PHP provides various methods and functions to handle file uploads, including the $_FILES superglobal variable, which stores information about the uploaded file.

How to Get File Type, Size, Extension Before Upload in PHP

  • Retrieving File Type
  • Retrieving File Size
  • Retrieving File Extension
  • Example 1: To get the file type, size, and extension before uploading it using PHP

Retrieving File Type

To retrieve the file type, you can use the mime_content_type() function in PHP. This function reads the first few bytes of the file and returns its MIME type.

$file_type = mime_content_type($_FILES['file']['tmp_name']);

The line of code $file_type = mime_content_type($_FILES[‘file’][‘tmp_name’]); retrieves the MIME type of the uploaded file. The mime_content_type() function is a built-in PHP function that takes the temporary file path of the uploaded file as an argument and returns the corresponding MIME type of the file.

Читайте также:  Python pandas replace string

MIME (Multipurpose Internet Mail Extensions) type is a standardized way of identifying files on the internet based on their nature and format. For example, the MIME type of a JPEG image is image/jpeg , while the MIME type of a PNG image is image/png . Knowing the MIME type of the uploaded file is important because it helps to ensure that the file is of the expected type and can be processed correctly.

In the context of file uploads, it is essential to validate the file type to prevent uploading malicious files such as executable files, scripts, or files with disguised extensions. The mime_content_type() function is a reliable method to retrieve the MIME type of the uploaded file as it uses the contents of the file to determine its type, rather than relying on the file extension.

Overall, the line of code $file_type = mime_content_type($_FILES[‘file’][‘tmp_name’]); is an essential step in retrieving the file type before uploading and validating the uploaded file to ensure the security and reliability of the web application.

Retrieving File Size

To retrieve the file size, you can use the filesize() function in PHP. This function returns the size of the file in bytes.

$file_size = filesize($_FILES['file']['tmp_name']);

In PHP, $file_size = filesize($_FILES[‘file’][‘tmp_name’]) is a line of code that retrieves the size of a file uploaded via a form.

  1. $_FILES is a superglobal array in PHP that contains information about uploaded files. It is populated when a user submits a file upload form.
  2. [‘file’] is the name attribute of the file input element in the form. It tells PHP which file to retrieve information about.
  3. [‘tmp_name’] is a property of the file element in the $_FILES array. It contains the path to the temporary file on the server where the uploaded file is stored before it is moved to its final destination.
  4. filesize() is a built-in PHP function that returns the size of a file in bytes. In this case, it takes the temporary file path as its argument and returns the file size in bytes.
  5. $file_size is a variable that stores the file size value returned by the filesize() function.

Overall, this line of code retrieves the size of an uploaded file in bytes and assigns it to the $file_size variable for further processing or validation. It is an important step in checking the file size before uploading it to the server to ensure that the server doesn’t run out of disk space or that the user doesn’t waste time uploading an excessively large file.

Retrieving File Extension

To retrieve the file extension, you can use the pathinfo() function in PHP. This function returns an array containing information about the file path, including the extension.

$file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); 

In the code $file_extension = pathinfo($_FILES[‘file’][‘name’], PATHINFO_EXTENSION); , the pathinfo() function in PHP is used to extract information about the file path. It takes two parameters: the file path and the information to be extracted.

In this case, $_FILES[‘file’][‘name’] is the file path of the uploaded file, and PATHINFO_EXTENSION is the constant that tells the function to return only the file extension.

The function returns an associative array containing information about the file path, including the file extension. The PATHINFO_EXTENSION constant ensures that only the extension is returned, which is then stored in the $file_extension variable.

For example, if the uploaded file has the name “document.pdf”, the pathinfo() function will return an array with the following elements:

Array ( [dirname] => [basename] => document.pdf [extension] => pdf [filename] => document )

Since you only want the extension, you pass the PATHINFO_EXTENSION constant as the second parameter to the pathinfo() function, which returns only the file extension “pdf” in this case.

This code is useful when you need to validate the file type based on its extension, which is often used to ensure that the uploaded file is of the expected format.

Example 1: To get the file type, size, and extension before uploading it using PHP

Putting it all together, here is an example of how to retrieve the file type, size, and extension before uploading it using PHP:

This PHP code is a basic implementation of file validation and upload. The code is triggered when a file is uploaded via a form and checks for three important parameters – file type, file size, and file extension – before proceeding with the upload.

The first condition in the code checks if a file has been uploaded via the form. If there is no file, the code will not execute any further. The next line retrieves the file type of the uploaded file by using the mime_content_type() function in PHP. This function reads the first few bytes of the file and returns its MIME type.

The following line retrieves the file size of the uploaded file by using the filesize() function in PHP. This function returns the size of the file in bytes.

The third line retrieves the file extension of the uploaded file by using the pathinfo() function in PHP. This function returns an array containing information about the file path, including the extension.

The next condition validates the file based on certain criteria. In this case, the code checks if the file type is either ‘image/jpeg’ or ‘image/png’, the file size is less than 1000000 bytes (1MB), and the file extension is ‘jpg’. If the file passes these checks, the code proceeds to upload the file to a specified directory using the move_uploaded_file() function in PHP. Otherwise, the code displays an error message.

In summary, this PHP code is a basic implementation of file validation and upload, where it checks the file type, size, and extension before proceeding with the upload. It is important to note that this code is just an example and should be adapted and extended to meet the specific needs of the application being developed.

Conclusion

To retrieving file type, size, and extension before uploading it is an important step when building a file upload feature in a web application. PHP provides various functions to handle file uploads, including getting the file type, size, and extension. Hope this article helps you in implementing a secure and efficient file upload feature on your website.

Источник

Массив $_FILES

В PHP-скрипте обработка загруженных через форму происходит через глобальный массив $_FILES , рассмотрим его содержимое:

Загрузка одного файла

Чтобы форма отправила файл, необходимо использовать только метод POST для отправки данных и добавить к тегу атрибут enctype=»multipart/form-data» , который определяет способ кодирования данных формы при их отправке на сервер.

Код скрипта index.php:

Результат:

Array( [name] => image.jpg [type] => image/jpeg [tmp_name] => /home/user/temp/phpjX2YXo [error] => 0 [size] => 119303 )

Описание значений массива $_FILES :

$_FILES[‘file-1’][‘name’] Оригинальное имя файла на компьютере клиента.
$_FILES[‘file-1’][‘type’] Mime-тип файла, в случае, если браузер предоставил такую информацию. Этот mime-тип не проверяется на стороне PHP, так что не полагайтесь на его значение без проверки.
$_FILES[‘file-1’][‘size’] Размер принятого файла в байтах .
$_FILES[‘file-1’][‘tmp_name’] Временное имя, с которым принятый файл был сохранен на сервере.
$_FILES[‘file-1’][‘error’] Код ошибки, которая может возникнуть при загрузке файла.

Загрузка несколько файлов

Для загрузки сразу нескольких файлов к нужно добавить атрибут multiple , а к имени поля – [] .

Код скрипта index.php

Результат:

Array( [name] => Array( [0] => image.jpg [1] => arhive.zip ) [type] => Array( [0] => image/jpeg [1] => application/zip ) [tmp_name] => Array( [0] => /home/user/temp/phpK3h32F [1] => /home/user/temp/phpBrGxus ) [error] => Array( [0] => 0 [1] => 0 ) [size] => Array( [0] => 119303 [1] => 6792 ) )

Как видно, структура массива разделена по свойствам, а не по файлам. Для удобства работы с циклом foreach массив $_FILES можно преобразовать:

 $l) < foreach($l as $i =>$v) < $files[$i][$k] = $v; >> $_FILES['file-2'] = $files; print_r($_FILES);

Результат:

Array( [0] => Array( [name] => image.jpg [type] => image/jpeg [tmp_name] => /home/user/temp/phpKgSQbo [error] => 0 [size] => 119303 ) [1] => Array( [name] => arhive.zip [type] => application/zip [tmp_name] => /home/user/temp/phpVht8LS [error] => 0 [size] => 6792 ) )

Максимальный размер загружаемого файла

Размер загружаемого файла можно ограничить, добавив в форму скрытое поле с максимальным размером файла :

В случае превышения размера файла в переменной $_FILES[‘file-1’][‘error’] будет ошибка с кодом « 2 ».

Коды ошибок загрузки файлов

В случаи, если при загрузке файла произошла ошибка, в переменной $_FILES[‘file’][‘error’] будет содержатся её код. Возможны следующие значения:

Код Константа Описание
0 UPLOAD_ERR_OK Ошибок не возникло, файл успешно загружен на сервер.
1 UPLOAD_ERR_INI_SIZE Размер файла превысил максимально допустимый размер, который задан директивой upload_max_filesize
2 UPLOAD_ERR_FORM_SIZE Размер загружаемого файла превысил значение MAX_FILE_SIZE, указанное в HTML-форме.
3 UPLOAD_ERR_PARTIAL Загружаемый файл был получен только частично.
4 UPLOAD_ERR_NO_FILE Файл не был загружен.
6 UPLOAD_ERR_NO_TMP_DIR Отсутствует временная папка.
7 UPLOAD_ERR_CANT_WRITE Не удалось записать файл на диск (возникает, когда на хостинге закончилось место).
8 UPLOAD_ERR_EXTENSION PHP-расширение остановило загрузку файла.

Настройки PHP

Обычно настройки загрузки файлов на хостинге вполне нормальные и не вызывают проблем, но есть исключения. Если не загружаются большие файлы, то скорее всего установлен лимит на размер загружаемого файла, ограничено время загрузки файла или ограничено количество одновременных загрузок.

Посмотреть установленные значения можно с помощью функции phpinfo() , в разделе «Core».

Раздел «Core» в phpinfo

В php.ini:

; Разрешение на загрузку файлов file_uploads = On ; Максимальное время выполнения скрипта в секундах max_execution_time = 60 ; Максимальное потребление памяти одним скриптом memory_limit = 64M ; Максимально допустимый размер данных отправляемых методом POST post_max_size = 50M ; Папка для хранения файлов во время загрузки upload_tmp_dir = home/user/temp ; Максимальный размер загружаемого файла upload_max_filesize = 5M ; Максимально разрешённое количество одновременно загружаемых файлов max_file_uploads = 10

В .htaccess:

# Разрешение на загрузку файлов php_value file_uploads On # Максимальное время выполнения скрипта в секундах php_value max_execution_time 60 # Максимальное потребление памяти одним скриптом php_value memory_limit 64M # Максимально допустимый размер данных отправляемых методом POST php_value post_max_size 50M # Папка для хранения файлов во время загрузки php_value upload_tmp_dir home/user/temp # Максимальный размер загружаемого файла php_value upload_max_filesize 5M # Максимально разрешённое количество одновременно загружаемых файлов php_value max_file_uploads 10

Источник

Оцените статью