Проверить формат файла php

mime_content_type

Возвращает MIME-тип содержимого файла, используя для определения информацию из файла magic.mime .

Список параметров

Путь к проверяемому файлу.

Возвращаемые значения

Возвращает тип содержимого в формате MIME, например text/plain или application/octet-stream или false в случае возникновения ошибки.

Ошибки

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

Примеры

Пример #1 Пример mime_content_type()

Результат выполнения данного примера:

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

User Contributed Notes 21 notes

Fast generation of uptodate mime types:

echo
generateUpToDateMimeArray ( APACHE_MIME_TYPES_URL );
?>

Output:
$mime_types = array(
‘123’ => ‘application/vnd.lotus-1-2-3’,
‘3dml’ => ‘text/vnd.in3d.3dml’,
‘3g2’ => ‘video/3gpp2’,
‘3gp’ => ‘video/3gpp’,
‘7z’ => ‘application/x-7z-compressed’,
‘aab’ => ‘application/x-authorware-bin’,
‘aac’ => ‘audio/x-aac’,
‘aam’ => ‘application/x-authorware-map’,
‘aas’ => ‘application/x-authorware-seg’,
.

There is a composer package that will do this:
https://github.com/ralouphie/mimey

$mimes = new \ Mimey \ MimeTypes ;

// Convert extension to MIME type:
$mimes -> getMimeType ( ‘json’ ); // application/json

// Convert MIME type to extension:
$mimes -> getExtension ( ‘application/json’ ); // json

and string detection on text files may fail if you check a file encoded with signed UTF-8. The UTF-8 signature is a two bytes code (0xFF 0xFE) that prepends the file in order to force UTF-8 recognition (you may check it on an hexadecimal editor).

For me mime_content_type didn’t work in Linux before I added

to php.ini (remember to find the correct path to mime.magic)

using
function detectFileMimeType ( $filename = » )
$filename = escapeshellcmd ( $filename );
$command = «file -b —mime-type -m /usr/share/misc/magic < $filename >» ;

$mimeType = shell_exec ( $command );

return trim ( $mimeType );
>
?>
should work on most shared linux hosts without errors. It should also work on Windows hosts with msysgit installed.

Lukas V is IMO missing some point. The MIME type of a file may not be corresponding to the file suffix.

Imagine someone would obfuscate some PHP code in a .gif file, the file suffix would be ‘GIF’ but the MIME would be text/plain or even text/html.

Another example is files fetched via a distant server (wget / fopen / file / fsockopen. ). The server can issue an error, i.e. 404 Not Found, wich again is text/html, whatever you save the file to (download_archive.rar).

His provided function should begin by the test of the function existancy like :

function MIMEalternative($file)
if(function_exists(‘mime_content_type’))
return mime_content_type($file);
else
return ($file);
>

I see a lot of comments suggesting doing file extension sniffing (i.e. assuming .jpg files are JPEG images) when proper file-type sniffing functions are unavailable.
I want to point out that there is a much more accurate way.
If neither mime_content_type() nor Fileinfo is available to you and you are running *any* UNIX variant since the 70s, including Mac OS, OS X, Linux, etc. (and most web hosting is), just make a system call to ‘file(1)’.
Doing something like this:
echo system ( «file -bi »» );
?>
will output something like «text/html; charset=us-ascii». Some systems won’t add the charset bit, but strip it off just in case.
The ‘-bi’ bit is important. However, you can use a command like this:
echo system ( «file -b »» ); // without the ‘i’ after ‘-b’
?>
to output a human-readable string, like «HTML document text», which can sometimes be useful.
The only drawback is that your scripts will not work on Windows, but is this such a problem? Just about all web hosts use a UNIX.
It is a far better way than just examining the file extension.

Читайте также:  Конвертировать html to doc

Here’s a simple function to return MIME types, based on the Apache mime.types file. [The one in my previous submission, which has since been replaced by this one] only works properly if mime.types is formatted as Windows text. The updated version below corrects this problem. Thanks to Mike for pointing this out.

function get_mime_type ( $filename , $mimePath = ‘../etc’ ) <
$fileext = substr ( strrchr ( $filename , ‘.’ ), 1 );
if (empty( $fileext )) return ( false );
$regex = «/^([\w\+\-\.\/]+)\s+(\w+\s)*( $fileext \s)/i» ;
$lines = file ( » $mimePath /mime.types» );
foreach( $lines as $line ) <
if ( substr ( $line , 0 , 1 ) == ‘#’ ) continue; // skip comments
$line = rtrim ( $line ) . » » ;
if (! preg_match ( $regex , $line , $matches )) continue; // no match to the extension
return ( $matches [ 1 ]);
>
return ( false ); // no match at all
>
?>

Notes:
[1] Requires mime.types file distributed with Apache (normally found at ServerRoot/conf/mime.types). If you are using shared hosting, download the file with the Apache distro and then upload it to a directory on your web server that php has access to.

[2] First param is the filename (required). Second parameter is path to mime.types file (optional; defaults to home/etc/). [3] Based on MIME types registered with IANA (http://www.iana.org/assignments/media-types/index.html). Recognizes 630 extensions associated with 498 MIME types. [4] Asserts MIME type based on filename extension. Does not examine the actual file; the file does not even have to exist. [5] Examples of use:
>> echo get_mime_type(‘myFile.xml’);
>> application/xml
>> echo get_mime_type(‘myPath/myFile.js’);
>> application/javascript
>> echo get_mime_type(‘myPresentation.ppt’);
>> application/vnd.ms-powerpoint
>> echo get_mime_type(‘http://mySite.com/myPage.php);
>> application/x-httpd-php
>> echo get_mime_type(‘myPicture.jpg’);
>> image/jpeg
>> echo get_mime_type(‘myMusic.mp3’);
>> audio/mpeg
and so on.

To create an associative array containing MIME types, use:
function get_mime_array ( $mimePath = ‘../etc’ )
<
$regex = «/([\w\+\-\.\/]+)\t+([\w\s]+)/i» ;
$lines = file ( » $mimePath /mime.types» , FILE_IGNORE_NEW_LINES );
foreach( $lines as $line ) <
if ( substr ( $line , 0 , 1 ) == ‘#’ ) continue; // skip comments
if (! preg_match ( $regex , $line , $matches )) continue; // skip mime types w/o any extensions
$mime = $matches [ 1 ];
$extensions = explode ( » » , $matches [ 2 ]);
foreach( $extensions as $ext ) $mimeArray [ trim ( $ext )] = $mime ;
>
return ( $mimeArray );
>
?>

Источник

filetype

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

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

Читайте также:  Css before with jquery

Ошибки

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

Примеры

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

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

Результат выполнения данного примера:

Примечания

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

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

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

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

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
» ;
?>

Читайте также:  Font family name in html

Источник

pathinfo

pathinfo() returns information about path : either an associative array or a string, depending on flags .

Note:

For information on retrieving the current path info, read the section on predefined reserved variables.

Note:

pathinfo() operates naively on the input string, and is not aware of the actual filesystem, or path components such as » .. «.

Note:

On Windows systems only, the \ character will be interpreted as a directory separator. On other systems it will be treated like any other character.

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

Parameters

If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION or PATHINFO_FILENAME .

If flags is not specified, returns all available elements.

Return Values

If the flags parameter is not passed, an associative array containing the following elements is returned: dirname , basename , extension (if any), and filename .

Note:

If the path has more than one extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one. (see first example below).

Note:

If the path does not have an extension, no extension element will be returned (see second example below).

Note:

If the basename of the path starts with a dot, the following characters are interpreted as extension , and the filename is empty (see third example below).

If flags is present, returns a string containing the requested element.

Examples

Example #1 pathinfo() Example

$path_parts = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );

echo $path_parts [ ‘dirname’ ], «\n» ;
echo $path_parts [ ‘basename’ ], «\n» ;
echo $path_parts [ ‘extension’ ], «\n» ;
echo $path_parts [ ‘filename’ ], «\n» ;
?>

The above example will output:

/www/htdocs/inc lib.inc.php php lib.inc

Example #2 pathinfo() example showing difference between null and no extension

$path_parts = pathinfo ( ‘/path/emptyextension.’ );
var_dump ( $path_parts [ ‘extension’ ]);

$path_parts = pathinfo ( ‘/path/noextension’ );
var_dump ( $path_parts [ ‘extension’ ]);
?>

The above example will output something similar to:

string(0) "" Notice: Undefined index: extension in test.php on line 6 NULL

Example #3 pathinfo() example for a dot-file

The above example will output something similar to:

Array ( [dirname] => /some/path [basename] => .test [extension] => test [filename] => )

Example #4 pathinfo() example with array dereferencing

The flags parameter is not a bitmask. Only a single value may be provided. To select only a limited set of parsed values, use array destructuring like so:

[ ‘basename’ => $basename , ‘dirname’ => $dirname ] = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );

var_dump ( $basename , $dirname );
?>

The above example will output something similar to:

string(11) "lib.inc.php" string(15) "/www/htdocs/inc"

See Also

  • dirname() — Returns a parent directory’s path
  • basename() — Returns trailing name component of path
  • parse_url() — Parse a URL and return its components
  • realpath() — Returns canonicalized absolute pathname

Источник

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