Content type by extension php

Get MIME Type From File Extension Using PHP

This tutorial will show you how you can get MIME type of a file using PHP program. Most of the times you may need to validate or check MIME type of a file when you upload a file for various reasons, such as, for KYC (Know Your Customer) purpose.

In this tutorial I have defined an array which holds almost all kinds of MIME type of files. So whenever you require to get the MIME type of a particular file then you can easily retrieve the MIME type of that file from this array.

Prerequisites

PHP 5.4/7.4.22/8.2.7
Apace http Server 2.4 (Optional)

Project Directory

It’s assumed that you have setup PHP in your system.

Now I will create a project root directory called php-file-mime anywhere in your system. I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project’s root directory.

Get MIME Type Of File

The following code checks the mime type for a given file name and returns the MIME type of the file. The following code is written into a file php-file-mime.php.

function mime_type($filename) < $mime_types = array( . 'smi' =>'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'wbxml' => 'application/wbxml', 'wmlc' => 'application/wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', . ); $ext = explode('.', $filename); $ext = strtolower(end($ext)); if (array_key_exists($ext, $mime_types)) < return (is_array($mime_types[$ext])) ? $mime_types[$ext][0] : $mime_types[$ext]; >else if (function_exists('finfo_open')) < if(file_exists($filename)) < $finfo = finfo_open(FILEINFO_MIME); $mimetype = finfo_file($finfo, $filename); finfo_close($finfo); return $mimetype; >> return 'application/octet-stream'; >

If multiple MIME types found for a particular file then the first MIME type is returned. If no MIME found for a particular file then default MIME type application/octet-stream is returned.

Usage

Here are some examples how to use the above function to get MIME type of a file:

$mime_type = mime_type('a.php'); echo $mime_type . "\n"; $mime_type = mime_type('final.doc'); echo $mime_type . "\n"; $mime_type = mime_type('inception.pdf'); echo $mime_type . "\n"; $mime_type = mime_type('meeting.jpg'); echo $mime_type . "\n"; $mime_type = mime_type('filename.xxx'); echo $mime_type . "\n"; $mime_type = mime_type('a.csv'); echo $mime_type . "\n"; $mime_type = mime_type('a.xl'); echo $mime_type . "\n";

The above code snippets will output as given in the below:

application/x-httpd-php application/msword application/pdf image/jpeg application/octet-stream text/x-comma-separated-values application/excel 

Источник

Читайте также:  Одномерный ассоциативный массив 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.

Читайте также:  Jquery добавить html содержимое

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

Источник

Get Mime-Type by file extension in PHP

Recently I build a PHP script for dynamically downloading files, and I came across the need to provide the right Mime-Type for each file I set to download. I wrote a function in PHP that gets file extension (with or without the dot prefix) and returns the correct Mime-Type.

Читайте также:  Php sql apache all in one

This function also returns the general purpose mime-type for missing or unknown file types.

General purpose MIME-TYPE

Use: application / octet — stream

case ‘.arc’ : $mime = ‘application/octet-stream’ ; break ; // Archive document (multiple files embedded)

case ‘.docx’ : $mime = ‘application/vnd.openxmlformats-officedocument.wordprocessingml.document’ ; break ; // Microsoft Word (OpenXML)

case ‘.js’ : $mime = ‘application/javascript’ ; break ; // JavaScript (IANA Specification) (RFC 4329 Section 8.2)

case ‘.mid’ : $mime = ‘audio/midi audio/x-midi’ ; break ; // Musical Instrument Digital Interface (MIDI)

case ‘.midi’ : $mime = ‘audio/midi audio/x-midi’ ; break ; // Musical Instrument Digital Interface (MIDI)

case ‘.odp’ : $mime = ‘application/vnd.oasis.opendocument.presentation’ ; break ; // OpenDocument presentation document

case ‘.ods’ : $mime = ‘application/vnd.oasis.opendocument.spreadsheet’ ; break ; // OpenDocument spreadsheet document

case ‘.odt’ : $mime = ‘application/vnd.oasis.opendocument.text’ ; break ; // OpenDocument text document

case ‘.pptx’ : $mime = ‘application/vnd.openxmlformats-officedocument.presentationml.presentation’ ; break ; // Microsoft PowerPoint (OpenXML)

case ‘.swf’ : $mime = ‘application/x-shockwave-flash’ ; break ; // Small web format (SWF) or Adobe Flash document

case ‘.xlsx’ : $mime = ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’ ; break ; // Microsoft Excel (OpenXML)

1 Comment

maya.kimhi

Leave a comment Cancel reply

You must be logged in to post a comment.

cute amateur anal and big cum facial in porn debut most beautiful pussy in the world gay my hero academia sex big ass trany porn clips

High definition xxx video of Vira doing anal Horny amateur teen peeing and masturbating on cam

This website uses cookies to improve your experience. We’ll assume you’re ok with this, but you can opt-out if you wish. Cookie settingsACCEPT

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are as essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

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