php get mime type file

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:

php get mime type file. Смотреть фото php get mime type file. Смотреть картинку php get mime type file. Картинка про php get mime type file. Фото php get mime type file

php get mime type file. Смотреть фото php get mime type file. Смотреть картинку php get mime type file. Картинка про php get mime type file. Фото php get mime type file

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_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.

Источник

How do I find the mime-type of a file with php?

How would I make that work correctly?

Should I test based on the extension of the file requested, or is there a way to get the filetype?

13 Answers 13

If you are sure you’re only ever working with images, you can check out the getimagesize() exif_imagetype() PHP function, which attempts to return the image mime-type.

If you don’t mind external dependencies, you can also check out the excellent getID3 library which can determine the mime-type of many different file types.

mime_content_type() is deprecated, so you won’t be able to count on it working in the future. There is a «fileinfo» PECL extension, but I haven’t heard good things about it.

If you are running on a *nix server, you can do the following, which has worked fine for me:

php get mime type file. Смотреть фото php get mime type file. Смотреть картинку php get mime type file. Картинка про php get mime type file. Фото php get mime type file

Anyway, using this specification, I was able to implement a mimesniffer in PHP. Performance is not an issue. In fact on my humble machine, I was able to open and sniff thousands of files before PHP timed out.

php get mime type file. Смотреть фото php get mime type file. Смотреть картинку php get mime type file. Картинка про php get mime type file. Фото php get mime type file

If you are working with Images only and you need mime type (e.g. for headers), then this is the fastest and most direct answer:

It will output true image mime type even if you rename your image file

According to the php manual, the finfo-file function is best way to do this. However, you will need to install the FileInfo PECL extension.

If the extension is not an option, you can use the outdated mime_content_type function.

php get mime type file. Смотреть фото php get mime type file. Смотреть картинку php get mime type file. Картинка про php get mime type file. Фото php get mime type file

You can use finfo to accomplish this as of PHP 5.3:

The FILEINFO_MIME_TYPE flag is optional; without it you get a more verbose string for some files; (apparently some image types will return size and colour depth information). Using the FILEINFO_MIME flag returns the mime-type and encoding if available (e.g. image/png; charset=binary or text/x-php; charset=us-ascii). See this site for more info.

php get mime type file. Смотреть фото php get mime type file. Смотреть картинку php get mime type file. Картинка про php get mime type file. Фото php get mime type file

I haven’t used it, but there’s a PECL extension for getting a file’s mimetype. The official documentation for it is in the manual.

Depending on your purposes, a file extension can be ok, but it’s not incredibly reliable since it’s so easily changed.

i got very good results using a user function from http://php.net/manual/de/function.mime-content-type.php @»john dot howard at prismmg dot com 26-Oct-2009 03:43»

which doesnt use finfo, exec or deprecated function

works well also with remote ressources!

if you’re only dealing with images you can use the [getimagesize()][1] function which contains all sorts of info about the image, including the type.

A more general approach would be to use the FileInfo extension from PECL. The PHP documentation for this extension can be found at: http://us.php.net/manual/en/ref.fileinfo.php

Some people have serious complaints about that extension. so if you run into serious issues or cannot install the extension for some reason you might want to check out the deprecated function mime_content_type()

Источник

Getting mime type of zipped files

Getting the mime type of an uploaded file is easy enough:

However, I also want to check the mime-type of files which are included in a zipped file. After unzipping my files (looping through the files in the zip and where i is the current file), I’ve tried:

which gives the error: Warning: mime_content_type() [function.mime-content-type]: File or path not found ‘.\foo.pdf’ in C:\Users\ \ \validation.php on line 56

I realised that the dirname for a zipped file is relative to the zip file, not the absolute path, so I tried:

which gives the error: Warning: mime_content_type() [function.mime-content-type]: File or path not found ‘C:\xampp\tmp\foo.pdf’ in C:\Users\ \ \validation.php on line 56

Can anyone cast any light on the path of the file? (I suspect the answer might be the same as the comment on getting image height and width from zipped files, but are there any alternative methods?)

UPDATE

Thanks to Baba, the following does work:

(n.b. I can only get this to work when I give the full route of the zip file, not a tmp file as would be the case when a file is uploaded via a form). However, trying to get the mime-type: echo mime_content_type($fp); generates the error:

This happens regardless of the file type (i.e. the problem stated in the only comment on http://php.net/manual/en/ziparchive.getstream.php doesn’t seem to affect me).

I know that there are several other ‘stream not supported’ questions on SO, but I couldn’t work out how they related to my problem, and I was hoping that since this method has been specifically suggested someone might have a good answer.

Источник

Как найти 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 любого файла на вашем сервере можно получить с помощью этого

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *