Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Fileinfo Functions

Fileinfo Functions

Introduction

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

Requirements

magic_open library is needed to build this extension.

Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/fileinfo

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FILEINFO_NONE (integer)
No special handling.
FILEINFO_SYMLINK (integer)
Follow symlinks.
FILEINFO_MIME (integer)
Return a mime string, instead of a textual description.
FILEINFO_COMPRESS (integer)
Decompress compressed files.
FILEINFO_DEVICES (integer)
Look at the contents of blocks or character special devices.
FILEINFO_CONTINUE (integer)
Return all matches, not just the first.
FILEINFO_PRESERVE_ATIME (integer)
If possible preserve the original access time.
FILEINFO_RAW (integer)
Don't translate unprintable characters to a \ooo octal representation.

Table of Contents

finfo_buffer — Return information about a string buffer
finfo_close — Close fileinfo resource
finfo_file — Return information about a file
finfo_open — Create a new fileinfo resource
finfo_set_flags — Set libmagic configuration options

Code Examples / Notes » ref.fileinfo

alexey

Well, it is hard to install and use this extension. There is better alternative - use lunux comand "file". For  insturctions - "man file" from linux shell.
<?
echo system("file -i -b file.pdf");
?>
application/pdf


danielwalker

Using the Unix 'file' program with the -i switch will not work reliably.
Consider the following plain-text CSV file (we'll call it 'error.csv'), which has the contents:
GIFT,WRAPPED,ERRORS,ON,LOOKING,At,FILES
...just that one line: nothing above it, nothing below.
Now, what does asking:
file -i error.csv
...give us for this file? Yes, that's right -
'error.csv: image/gif'
Why? Because the first line starts 'GIF...', that's why. You cannot trust file.


jon

To get v1.0.4 working on my Ubuntu Feisty system, I had to do the following. It's probably the same on Debian.
* apt-get install libmagic1-dev
* pecl install Fileinfo
* Add "extension=fileinfo.so" to php.ini (/etc/php5/{cli,cgi}/php.ini)
* ln -s /usr/share/file/magic /etc/magic.mime


bob

This is the most impossible module to get functioning.  There's about zero way to get it to function on OS X, and it's supposed to be the de facto way to pull mime types and other file info?
Seriously, the whole thing and all dependencies need to be bundled with PHP.


paul

The results of this function seem to be of dubious quality.
eg
1)  a Word doc returns:
'application/msword application/msword'
...ok not too bad, but why does it come back twice?
2)  a PHP file comes back as:
'text/x-c++; charset=us-ascii'
My test file started with '<?php' so not ambiguous really. And where does it get the charset assumption from?
3)  a text doc that starts with the letters 'GIF' comes back as:
'image/gif'
(just like in DanielWalker's example for the unix 'file' command)
I had better results using the PEAR 'MIME_Type' package. It gave proper answers for 1 & 3 and identified the PHP file as 'text/plain' which is probably better than a false match for C++
Both finfo_file and MIME_Type correctly identified my other two test files which were a windows exe renamed with .doc extension, and a PDF also renamed with .doc extension.


deanariel

Sometime "pear install fileinfo" won't work....
so you can try "pear install pecl/fileinfo"


aidan

PHP Warning:  finfo::finfo(): Failed to load magic database at '/etc/magic'
PHP Warning:  finfo::file(): The invalid fileinfo object
These errors can be rectified by copying your magic database (depending on your distro, this file can be anywhere, on debian it's in /usr/share/file/magic) to /etc/magic.mime
libmagic automatically appends the .mime to the end of the filename, so PHP incorrectly reports the path it was looking for.
The same applies for:
PHP Warning:  finfo::finfo(): Failed to load magic database at '/etc/magic.mime'
Unfortunately users will have to call the magic file /etc/magic.mime.mime in this case.


bujuzu a~t gmail.com

If, like I was, you are looking for a quick and easy way to grab a mime type on a file, and don't feel like fiddling around with extentions or pear or any of that, a unix native 'file -i' command will usually do the trick - that is, if you are able to use shell commands.

motin

I had a real headache trying to install this package through pear/pecl. Ran into what looks like this bug: http://pecl.php.net/bugs/bug.php?id=7673 (phpize fails)
I found downloading the package manually and running ./configure helped show what the problem is:
...
checking for fileinfo support... yes, shared
checking for magic files in default path... not found
configure: error: Please reinstall the libmagic distribution
<quit>
I though this was because of a missing magic-database like magic.mime but examining the configure-script, magic.h is searched for.
Problem for me was that include/magic.h was not found. After some googling about where to find magic.h led me to the dead
simple solution:
apt-get install libmagic-dev
This does NOT solve the original installation bug strangely enough, but allows for manual installation:
1. Find the url to the latest version of fileinfo from http://pecl.php.net/package/Fileinfo (atm: http://pecl.php.net/get/Fileinfo-1.0.4.tgz)
2. Download, compile and install
wget http://pecl.php.net/get/Fileinfo-1.0.4.tgz
gunzip Fileinfo-1.0.4.tgz
tar -xvf Fileinfo-1.0.4.tar
cd fileinfo-1.0.4
./configure
make
make install
3. Add extension=fileinfo.so in your php.ini file
4. Restart Apache


szotsaki

I am about to write how installed this package.
First of all, I tried with "pear install fileinfo" - as the manual says.
But the pear command said that 'Package "Fileinfo" is not valid,
install failed'.
Then the "pear install pecl/fileinfo" was a better way. But at that time the "phpize" command was missing.
I installed that (on openSUSE distributions it is in the php5-devel, but I think you can find it in your distro's corresponding php-devel package).
After that you may install "re2c" (I did). It's homepage is: http://sourceforge.net/projects/re2c
Copy the magic file of Apache (usually in /etc/apache2) into the following directory: /usr/locale/share/file/ or /usr/share/file/
Then you have to install "libmagic-dev". If you have Debian based system you can simply install it with apt.
But if you have an rpm based system (like me), you have to download the following package: http://packages.debian.org/unstable/libdevel/libmagic-dev
It contains the files we need.
So, download the file, browse it with Midnight Commander (mc) (you have to apt and dpkg be installed) and simply extract (so copy) the /usr folder (it is inside the CONTENTS folder) of the .deb package to the root folder.
And now give the "pear install pecl/fileinfo" command another try :)
Ps: Don't forget to check whether the script has wrote the following line into the php.ini (on openSUSE: /etc/php5/apache2): extension=fileinfo.so
I hope, I could help.


johny

Here is a mistake:
No:
----
pear install fileinfo
----
but
----
pecl install fileinfo
----


jausions

For Windows users:
1. Go to http://pecl4win.php.net/ to get the php_fileinfo.dll if your PHP installation didn't come with it, and you haven't installed the Extensions package.
2. Then make sure you have extension=php_fileinfo.dll somewhere in your php.ini
3. Restart your web server.


mwwaygoo

Be careful of using   system("file -i -b file.pdf");
I got some strange results as follows:-
1.
<?php
$type=system("file -i -b mime.php");
echo $type;
?>
text/plain; charset=us-ascii
text/plain; charset=us-ascii
2.
<?php
$type=system("file -i -b mime.php");
echo $type."<br/>\n";
$split=split(";",$type);
print_r($split);
$type=trim($split[0]);
echo $type;
?>
text/plain; charset=us-ascii
text/plain; charset=us-ascii<br/>
Array
(
   [0] => text/plain
   [1] =>  charset=us-ascii
)
text/plain
3.
<?php
$type=@system("file -i -b mime.php");
//echo $type."<br/>\n";   // just comment this line
$split=split(";",$type);
print_r($split);
$type=trim($split[0]);
echo $type;
?>
text/x-c++; charset=us-ascii
Array
(
   [0] => text/x-c++
   [1] =>  charset=us-ascii
)
text/x-c++


hari_1983

Actually for RPM users file-devel contains whatever libmagic contains. then apart from pear, u can directly use "pecl install Fileinfo".

Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker