Determine file type in php

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

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.

Источник

filetype

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown.

Returns false if an error occurs. filetype() will also produce an E_NOTICE message if the stat call fails or if the file type is unknown.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 filetype() example

echo filetype ( ‘/etc/passwd’ );
echo «\n» ;
echo filetype ( ‘/etc/’ );

The above example will output:

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_dir() — Tells whether the filename is a directory
  • is_file() — Tells whether the filename is a regular file
  • is_link() — Tells whether the filename is a symbolic link
  • file_exists() — Checks whether a file or directory exists
  • mime_content_type() — Detect MIME Content-type for a file
  • pathinfo() — Returns information about a file path
  • stat() — Gives information about a file

User Contributed Notes 6 notes

There are 7 values that can be returned. Here is a list of them and what each one means

block: block special device

char: character special device

unknown: unknown file type

filetype() does not work for files >=2GB on x86 Linux. You can use stat as a workarround:

Note that stat returns diffenerent strings («regular file»,»directory». )

I use the CLI version of PHP on Windows Vista. Here’s how to determine if a file is marked «hidden» by NTFS:

function is_hidden_file ( $fn )

$attr = trim ( exec ( ‘FOR %A IN («‘ . $fn . ‘») DO @ECHO %~aA’ ));

if( $attr [ 3 ] === ‘h’ )
return true ;

This should work on any Windows OS that provides DOS shell commands.

Putting @ in front of the filetype() function does not prevent it from raising a warning (Lstat failed), if E_WARNING is enabled on your error_reporting.

The most common cause of filetype() raising this warning and not showing a filetype() in the output (it actually returns NULL) is, if you happened to pass just the ‘Dir or File Name’ and not the complete «Absolute or Relative Path» to that ‘file or Dir’. It may still read that file and return its filetype as «file» but for Dir’s it shows warning and outputs NULL.
eg:
$pathToFile = ‘/var/www’;
$file = ‘test.php’;
$dir = ‘somedir’;

Output for filetype($file) will be returned as ‘file’ and possibly without any warning, but for filetype($dir), it will return NULL with the warning «Lstat failed», unless you pass a complete path to that dir, i.e. filetype($pathToFile.’/’.$dir).

This happened to me and found this solution after a lot of trial and error. Thought, it might help someone.

Note there is a bug when using filetype with for example Japanese filenames :
https://bugs.php.net/bug.php?id=64699

The whole PHP interpreter comes crashing down without anyway to avoid it or capture an exception.

echo «Zum testen müssen tatsächlich existente Namen verwendet werden.
» ;
echo «Pfad und Dateiname müssen getrennt eingetragen und durch einen Punkt verbunden sein.
» ;
echo «Example: [filetype(\»../dir/u_dir/\».\»temp.jpg\»)] liefert -> file
» ;
?>

Источник

filetype

Возвращает тип файла. Возможными значениями являются fifo, char, dir, block, link, file, socket и unknown.

Возвращает FALSE в случае ошибки. filetype() также вызовет ошибку уровня E_NOTICE , если системный вызов stat завершится ошибкой или тип файла неизвестен.

Примеры

Пример #1 Пример использования функции filetype()

echo filetype ( ‘/etc/passwd’ ); // file
echo filetype ( ‘/etc/’ ); // dir

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Примечания

Замечание: Результаты этой функции кэшируются. Более подробную информацию смотрите в разделе clearstatcache() .

Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обертками url. Список оберток, поддерживаемых семейством функций stat() , смотрите в Поддерживаемые протоколы и обработчики (wrappers).

Смотрите также

  • is_dir() — Определяет, является ли имя файла директорией
  • is_file() — Определяет, является ли файл обычным файлом
  • is_link() — Определяет, является ли файл символической ссылкой
  • file_exists() — Проверяет наличие указанного файла или каталога
  • mime_content_type() — Определяет MIME-тип содержимого файла (устаревшее)
  • pathinfo() — Возвращает информацию о пути к файлу
  • stat() — Возвращает информацию о файле

Источник

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