php тип файла mime
mime_content_type
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
mime_content_type — Определяет MIME-тип содержимого файла
Описание
Список параметров
Путь к проверяемому файлу.
Возвращаемые значения
Возвращает тип содержимого в формате MIME, например text/plain или application/octet-stream или false в случае возникновения ошибки.
Ошибки
Примеры
Пример #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
= new \ Mimey \ MimeTypes ;
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)
Lukas V is IMO missing some point. The MIME type of a file may not be corresponding to the file suffix.
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);
>
Regarding serkanyersen’s example : It is advisable to change the regular expression to something more precise like
This makes sure that only the last few characters are taken. The original expression would not work if the filename is a relative path.
if(! function_exists ( ‘mime_content_type’ )) <
<>
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.
[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.
On Windows, PHP 7.0.30 gave the error message «Fatal error: Uncaught Error: Call to undefined function mime_content_type()». I saw the following interesting line in my Apache configuration:
#LoadModule mime_magic_module modules/mod_mime_magic.so
so I tried uncommenting it and restarting the Apache service, but still got the same error. A Web search shows that this function is deprecated. It appears to have been removed from PHP. Not sure why, but can be worked around with a user function.
The correct little correction:
exec will return the mime with a newline at the end, the trim() should be called with the result of exec, not the other way around.
I added these two lines to my magic.mime file:
// Here is a working version of a function that fetches the meme types from apache’s built in mime list and creates an array of which the keys are the file extensions:
function generateUpToDateMimeArray($url) <
$return = array();
$mimes = file_get_contents(‘http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types’); // make sure that allow_url_fopen is enabled!
I also had issues with this function.
The issue was that it would almost always return «text/plain».
echo ini_get(‘mime_magic.magicfile’); // returns /etc/httpd/conf/magic
I found that I needed the OS’ magic.mime file instead.
You can either copy it to the existing location, or update your php.ini, you cannot use ini_set().
[root@blade conf]# mv magic magic.old
[root@blade conf]# cp /usr/share/magic.mime magic
[root@blade conf]# apachectl graceful
Note: you will see that I have gracefully restarted apache to ensure it has taken affect.
PHP: How to properly check MIME type of a file?
I have an input where you can upload images, the only allowed images types are:
before the image is inserted to the database it checks if the pictures are png,jpg,jpeg. But now for security reasons I need to check the mime type before or after the first check.
How do I do this? This is my code:
2 Answers 2
So I recommend that you do not depend on the following snippet to get MIME of a file
Rather I would recommend use this mime_content_type() function to get MIME type but with the help of other PHP’s built-in function. And that is is_uploaded_file() function. What it does is:
This is useful to help ensure that a malicious user hasn’t tried to trick the script into working on files upon which it should not be working—for instance, /etc/passwd.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
So to make this function work properly it needs a specific argument. Check out the code below:
This function returns true on success, false otherwise. So if it returns true then you’re ok with the file. Thanks to this function. Now mime_content_type() function comes into play. How? Look at the code below:
BTW, for novice, do not try remote url with this function to get MIME type. The code below will not work:
But the one below would work:
Hope you would enjoy uploading file from now on.
Как найти MIME-тип файла с php?
как бы я сделал это правильно?
должен ли я тестировать на основе расширения запрашиваемого файла или есть способ получить тип файла?
13 ответов
Если вы уверены, что работаете только с изображениями, вы можете проверить getimagesize() exif_imagetype () PHP функция, которая пытается вернуть изображение mime-типа.
Если вы не против внешних зависимостей, вы также можете проверить отличные getID3 библиотека, которая может определить MIME-тип многих различных типов файлов.
наконец, вы можете проверить mime_content_type () функция-но она была устаревшей для Fileinfo расширение PECL.
mime_content_type () устарел, поэтому вы не сможете рассчитывать на его работу в будущем. Существует расширение «fileinfo» PECL, но я не слышал о нем хороших вещей.
Если вы работаете на сервере *nix, вы можете сделать следующее, что отлично сработало для меня:
в любом случае, используя эту спецификацию, я смог реализовать mimesniffer в PHP. Производительность не является проблемой. На самом деле на моей скромной машине я смог открыть и понюхать тысячи файлов до версии PHP истекло.
Если вы работаете только с изображениями, и вам нужен тип mime (например, для заголовков), то это самый быстрый и самый прямой ответ:
Он выведет true image mime type, даже если вы переименуете файл изображения
согласно руководству php,finfo-file функция-лучший способ сделать это. Тем не менее, вам нужно будет установить FileInfo на расширение PECL.
Если расширение не подходит, вы можете использовать устаревший mime_content_type
вы можете использовать finfo для выполнения этого с PHP 5.3:
флаг FILEINFO_MIME_TYPE является необязательным; без него вы получаете более подробную строку для некоторых файлов; (по-видимому, некоторые типы изображений будут возвращать информацию о размере и глубине цвета). Использование флага FILEINFO_MIME возвращает MIME-тип и кодировку, если они доступны (например, image/png; charset=binary или text/x-php; charset=US-ascii). См.этот сайт для получения дополнительной информации.
Я не использовал его, но есть расширение PECL для получения типа mimetype файла. Официальная документация для него находится в руководство.
в зависимости от ваших целей расширение файла может быть в порядке, но оно не невероятно надежно, так как его так легко изменить.
Я получил очень хорошие результаты, используя пользовательскую функцию от http://php.net/manual/de/function.mime-content-type.php @»john dot howard at prismmg dot com 26-Oct-2009 03: 43″
который не использует finfo, exec или устаревшую функцию
хорошо работает и с удаленными ресурсами!
Если вы имеете дело только с изображениями, которые вы можете использовать [getimagesize()][1] функция, которая содержит все виды информации об изображении, включая тип.
более общим подходом было бы использовать расширение FileInfo из PECL. Документацию по PHP для этого расширения можно найти по адресу:http://us.php.net/manual/en/ref.fileinfo.php
некоторые люди имеют серьезные жалобы на это расширение. поэтому, если вы столкнулись с серьезными проблемами или не можете установить расширение по какой-то причине вы можете проверить устаревшую функцию mime_content_type()
Если вы запускаете Linux и имеете расширение, вы можете просто прочитать тип MIME из /etc/mime.типы путем создания хэш-массива. Затем вы можете сохранить это в памяти и просто вызвать MIME с помощью ключа массива:)
mime любого файла на вашем сервере можно получить с помощью этого
Загрузка файла PHP: проверка на основе MIME или расширения?
когда я пытаюсь обработать загрузку файла, должен ли я запускать проверку на основе типа файла MIME или расширения файла?
каковы плюсы и минусы этих 2 способов проверки файлов?
и, любые другие вопросы безопасности должны меня беспокоить?
в эти дни я полагался на тип MIME, но ответ с большинством голосов в этом посте
никогда не полагайтесь на тип MIME отправлено браузером!
4 ответов
хорошо, так что для всех гениев здесь тявкают что-то о «винт расширения, проверьте МИМ! FILEINFO НА РЛЗ!», Я подготовил учебник:
EDIT: не-как-необычный-код-как-вы-хотите-это-быть, который открывает веб-сайт для этого тип атаки:
MIME-тип не является надежным источником, потому что он отправляет из браузера (также любой может создать HTTP-запрос вручную). PHP не проверял эквивалентность расширения и типа mine (http://ru.php.net/manual/en/features.file-upload.post-method.php). Вы можете акцентировать HTTP-запрос с именем файла » image.php «и mime-тип «изображение / gif».
используйте always verification by extension, если вы хотите сохранить загруженный файл на HDD и предоставить публичный доступ к этому файлу позже.
теперь для проверки, ответ на вопрос зависит от того, почему вы хотите проверить тип файла.
чтобы точно определить, что было загружено, вы не проверяете расширение файла или тип mime, отправленный обозреватель.
в среде * nix у вас есть утилита для проверки типа mime данного файла, обычно расположенного в magic.файл mime (/usr/share / magic.mime или что-то подобное, в зависимости от вашей настройки).
Копировать / Вставить из magic.мим Итак, вы видите, как это работает в двух словах:
Я свяжу вы со ссылкой, которая поможет вам в дальнейшей реализации в PHP (буквально 2 строки кода, как только вы закончите).
Если вы не можете заставить его работать после всего этого, напишите здесь в комментариях, и я предоставлю полный код, необходимый для безопасного обнаружения того, что было загружено.
image_type_to_mime_type
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
image_type_to_mime_type — Получение Mime-типа для типа изображения, возвращаемого функциями getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
Описание
Функция image_type_to_mime_type() определяет Mime-тип для константы IMAGETYPE.
Список параметров
Возвращаемые значения
Возвращаемые значения приведены ниже
image_type | Возвращаемое значение |
---|---|
IMAGETYPE_GIF | image/gif |
IMAGETYPE_JPEG | image/jpeg |
IMAGETYPE_PNG | image/png |
IMAGETYPE_SWF | application/x-shockwave-flash |
IMAGETYPE_PSD | image/psd |
IMAGETYPE_BMP | image/bmp |
IMAGETYPE_TIFF_II (порядок байт intel) | image/tiff |
IMAGETYPE_TIFF_MM (порядок байт motorola) | image/tiff |
IMAGETYPE_JPC | application/octet-stream |
IMAGETYPE_JP2 | image/jp2 |
IMAGETYPE_JPX | application/octet-stream |
IMAGETYPE_JB2 | application/octet-stream |
IMAGETYPE_SWC | application/x-shockwave-flash |
IMAGETYPE_IFF | image/iff |
IMAGETYPE_WBMP | image/vnd.wap.wbmp |
IMAGETYPE_XBM | image/xbm |
IMAGETYPE_ICO | image/vnd.microsoft.icon |
IMAGETYPE_WEBP | image/webp |
Примеры
Пример #1 Пример использования image_type_to_mime_type()