Php function get file type

PHP filetype() Function

Solution 1: You can use PHP’s Fileinfo to detect file types based on their contents; however, it is only available in PHP 5.3.0 or if you have access to install PECL extensions. Third, you should where possible determine the contents of the file yourself rather than relying on either the file extension or the MIME type (from file uploads).

PHP | filetype( ) Function

The filetype() function in PHP is an inbuilt function which is used to return the file type of a specified file or a directory.

The filetype() function accepts the filename as a parameter and returns one of the seven file types on success and False on failure.

The seven possible return values of the filetype() function are:

  • file: regular file
  • dir: directory
  • char: character special device
  • link: symbolic link
  • fifo: FIFO (named pipe)
  • block: block special device
  • unknown: unknown file type

The result of the filetype() function is cached and a function called clearstatcache() is used to clear the cache.

Parameters: The filetype() function in PHP accepts only one parameter $filename . It specifies the filename of the file whose type you want to know.

Return Value: It returns the type of a file on success and False on failure.

Errors And Exception :

  1. For files which are larger than 2GB some filesystem functions may return unexpected results since PHP’s integer type is signed and many platforms use 32bit integers.
  2. The filetype() function emits an E_WARNING in case of a failure.
  3. The buffer must be cleared if the filetype() function is used multiple times.
  4. The filetype() function emits an E_NOTICE message if the stat call fails or if the file type is unknown.
Input : filetype("gfg.txt"); Output : fileInput : filetype("documents"); Output : dir

Below programs illustrate the filetype() function.

Reference:
http://php.net/manual/en/function.filetype.php

PHP- Get file type by URL,

How to get the file type in PHP

I have a .doc file and I renamed named it to give it a .jpg extension. When I process the renamed file with my function it accepts the file as having a .jpg although the file is not really a JPEG. What’s the best way to find the actual file type? Here is my current code:

function getExtension($str) < $i = strrpos($str,"."); if (!$i) < return ""; >$l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; > 

What’s the best way to check the file’s type without depending on the extension?

You can use PHP’s Fileinfo to detect file types based on their contents; however, it is only available in PHP 5.3.0 or if you have access to install PECL extensions.

It returns a file’s mime-type, such as text/html, image/gif, or application/vnd.ms-excel which should be more accurate (accounts for contents possibly having multiple common extensions, such as: jpg, jpe, jpeg).

This is the one I use and it has never failed me.

I don’t know if you can check the actual original file extension if someone has renamed it, you would have to have the spec of every file type you were checking for I’m not sure how easy it is to tell. But you could verify something was an image like this:

if(isImage($file) && getExtention($file) == "jpg") < //Process, it's a valid image >

Firstly, with respect to file extension, on’t reinvent the wheel. Use PHP’s pathinfo() function:

$extension = pathinfo($filename, PATHINFO_EXTENSION); 

Secondly, you’re quite right: the file extension tells you nothing about it’s contents.

Third, you should where possible determine the contents of the file yourself rather than relying on either the file extension or the MIME type (from file uploads). Both are arbitrary and simply specified by the client.

Images are fairly easy because you can load the file with the GD library. It’ll fail if its not an image and you can interrogate it for size, etc.

Word documents are harder. If you’re running on Windows, you can make a call to the system to load the file and see if it does load. I’m not aware of any native PHP library that can do this.

If you just want to get the file extension, you could use pathinfo :

However, it sounds like you want to check if the file you’re given is a valid image. To do that, you can do something similar with the getimagesize() function:

function getMimeType($str) < $info = @getimagesize($str) if (!$info) < // Uh oh, this wasn't a valid image -- do some error handling return NULL; >return $info['mime']; > 

Using this, you can check the MIME type of the image («image/jpeg», etc.), and validate if the given file is really the type of image you think it is.

How to get the file extension in PHP? [duplicate], $userfile_name = $_FILES[‘image’][‘name’]; $userfile_extn = explode(«.», strtolower($_FILES[‘image’][‘name’]));. Is there a way to just get the

PHP- Get file type by URL

I want to get the file type (eg. image/gif) by URL using PHP.I had tried

The above code gave me a blank page and the following code returned «3»:

Where am I going wrong? Solved: using Fileinfo to fetch content type

Here is a PHP function I came up with:

/** * @param $image_path * @return bool|mixed */ function get_image_mime_type($image_path) < $mimes = array( IMAGETYPE_GIF =>"image/gif", IMAGETYPE_JPEG => "image/jpg", IMAGETYPE_PNG => "image/png", IMAGETYPE_SWF => "image/swf", IMAGETYPE_PSD => "image/psd", IMAGETYPE_BMP => "image/bmp", IMAGETYPE_TIFF_II => "image/tiff", IMAGETYPE_TIFF_MM => "image/tiff", IMAGETYPE_JPC => "image/jpc", IMAGETYPE_JP2 => "image/jp2", IMAGETYPE_JPX => "image/jpx", IMAGETYPE_JB2 => "image/jb2", IMAGETYPE_SWC => "image/swc", IMAGETYPE_IFF => "image/iff", IMAGETYPE_WBMP => "image/wbmp", IMAGETYPE_XBM => "image/xbm", IMAGETYPE_ICO => "image/ico"); if (($image_type = exif_imagetype($image_path)) && (array_key_exists($image_type ,$mimes))) < return $mimes[$image_type]; >else < return FALSE; >> 

It returned 3 because png response type as maciej said.

Try this to get like this image/png :

echo mime_content_type($image_path); 
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension echo finfo_file($finfo, $image_path) . "\n"; finfo_close($finfo); 

the best way for my understanding

if (!function_exists('getUrlMimeType')) < function getUrlMimeType($url) < $buffer = file_get_contents($url); $finfo = new finfo(FILEINFO_MIME_TYPE); return $finfo->buffer($buffer); > > 

is to create function depend on finfo class

You are not going wrong anywhere. exif_imagetype returns the value of one of the image type constants: http://php.net/manual/en/image.constants.php

If you would like to convert this to an extension string, you could use a switch statement:

$typeString = null; $typeInt = exif_imagetype($image_path); switch($typeInt) < case IMG_GIF: $typeString = 'image/gif'; break; case IMG_JPG: $typeString = 'image/jpg'; break; case IMG_JPEG: $typeString = 'image/jpeg'; break; case IMG_PNG: $typeString = 'image/png'; break; case IMG_WBMP: $typeString = 'image/wbmp'; break; case IMG_XPM: $typeString = 'image/xpm'; break; default: $typeString = 'unknown'; >

You may want to change the order to most to least frequently expected for better performance.

Check file extension in upload form in PHP [duplicate],

Источник

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() — Возвращает информацию о файле

Источник

Читайте также:  Deep compare dict python
Оцените статью