Fonctions Fileinfo

Sommaire

add a note add a note

User Contributed Notes 14 notes

up
5
ccbsschucko at gmail dot com
5 years ago
<?php
   
class FileInfoTool {

       
/**
        * @var str => $file = caminho para o arquivo (ABSOLUTO OU RELATIVO)
        * @var arr => $file_info = array contendo as informações obtidas do arquivo informado
        */
       
private $file;
        private
$file_info;

       
/**
        * @param str => $file = caminho para o arquivo (ABSOLUTO OU RELATIVO)
        */
       
public function get_file(string $file){
           
clearstatcache();
           
$file = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $file);
            if(!
is_file($file) && !is_executable($file) && !is_readable($file)){
                throw new \
Exception('O arquivo informado não foi encontrado!');
            }
           
$this->file = $file;
           
$this->set_file_info($this->file);
            return
$this;
        }

       
/**
        * @param str => $index = se for informado um indice é retornada uma informação específica do arquivo
        */
       
public function get_info($index = ''){
            if(
$this->get_file_is_called()){
                if(
$index === ''){
                    return
$this->file_info;
                }
                if(
$index != ''){
                    if(!
array_key_exists($index, $this->file_info)){
                        throw new \
Exception('A informação requisitada não foi encontrada!');                   
                    }
                    return
$this->file_info;
                }
            }
        }

       
/**
        * @todo verifica se o método get_file() foi utilizado para informar o caminho do arquivo
        */
       
private function get_file_is_called(){
            if(!
$this->file){
                throw new \
Exception('Nenhum arquivo foi fornecido para análise. Utilize o método get_file() para isso!');
                return
false;
            }
            return
true;
        }

       
/**
        * @todo preencher a array com as infos do arquivo
        */
       
private function set_file_info(){
           
$this->file_info = array();
           
$pathinfo = pathinfo($this->file);
           
$stat = stat($this->file);
           
$this->file_info['realpath'] = realpath($this->file);
           
$this->file_info['dirname'] = $pathinfo['dirname'];
           
$this->file_info['basename'] = $pathinfo['basename'];
           
$this->file_info['filename'] = $pathinfo['filename'];
           
$this->file_info['extension'] = $pathinfo['extension'];
           
$this->file_info['mime'] = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file);
           
$this->file_info['encoding'] = finfo_file(finfo_open(FILEINFO_MIME_ENCODING), $this->file);
           
$this->file_info['size'] = $stat[7];
           
$this->file_info['size_string'] = $this->format_bytes($stat[7]);
           
$this->file_info['atime'] = $stat[8];
           
$this->file_info['mtime'] = $stat[9];
           
$this->file_info['permission'] = substr(sprintf('%o', fileperms($this->file)), -4);
           
$this->file_info['fileowner'] = getenv('USERNAME');
        }

       
/**
        * @param int => $size = valor em bytes a ser formatado
        */
       
private function format_bytes(int $size){
           
$base = log($size, 1024);
           
$suffixes = array('', 'KB', 'MB', 'GB', 'TB');  
            return
round(pow(1024, $base-floor($base)), 2).''.$suffixes[floor($base)];
        }
    }

   
var_dump((new FileInfoTool)->get_file('sitemap.xml')->get_info());
?>
up
13
Paul
16 years ago
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.
up
1
jon at cybus dot co dot uk
16 years ago
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
up
3
Terren Suydam
15 years ago
If finfo_file() returns a mime type that also includes a character set definition (separated by a semi-colon), like:

text/plain; charset=us-ascii

Then you'll probably want to leave the charset definition in with the mime type, particularly if you're using the resulting string in an HTTP Content-Length header. The HTTP standard specifically allows for this, see:

http://www.w3.org/International/O-HTTP-charset

It seemed as if some of the previous commenters were trying to remove the charset.
up
0
Evermorian
15 years ago
In response to the suggestion from "jon at cybus" below to symlink /usr/share/file/magic to /etc/magic.mime, note that this causes other problems (in Debian Etch, anyway).  It breaks the -i functionality of the file command, causing it to return the human-readable string instead of the MIME type.  It also results in finfo doing the same.

So, it is probably better to actually specify the path to the magic file correctly when instantiating your finfo object:

<?php
$fi
= new finfo(FILEINFO_MIME,'/usr/share/file/magic');
$mime_type = $fi->buffer(file_get_contents($file));
?>

Of course, you still end up with something that cannot tell the difference between a Word document and an Excel spreadsheet.
up
-1
szotsaki at gmail dot com
17 years ago
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.
up
-1
aidan at php dot net
17 years ago
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.
up
-1
motin at demomusic dot nu
17 years ago
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
up
-2
aidan at php dot net
15 years ago
As of PHP 5.3, Fileinfo is shipped with the main distribution and enabled by default. The extension is no longer maintained in PECL.
up
-2
jausions at php dot net
17 years ago
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.
up
-1
bostjan at a2o dot si
13 years ago
'Failed to load magic database at...'

This error message may be caused by incompatibilities between library and database. Check your database by trying to compile it with file command, like this:

cd /etc/magic
file -C -m magic
file -C -m magic.mime

b.
up
-4
Alexey
17 years ago
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
up
-4
nessi at nessi dot ch
14 years ago
For opensuse, you will just need to install the file-devel to solve the Problem with
checking for magic files in default path... not found
configure: error: Please reinstall the libmagic distribution

zypper install file-devel
up
-7
hari_1983 at yahoo dot com
16 years ago
Actually for RPM users file-devel contains whatever libmagic contains. then apart from pear, u can directly use "pecl install Fileinfo".
To Top