downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

finfo_set_flags> <finfo_file
[edit] Last updated: Fri, 25 May 2012

view this page in

finfo_open

finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_open -- finfo::__constructCrea un nuevo recurso fileinfo

Descripción

Estilo por procedimientos

resource finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

Estilo orientado a objetos (constructor):

finfo::__construct() ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

Esta función abre una base de datos mágica y la devuelve a su recurso.

Parámetros

options

Una o más constantes Fileinfo .

magic_file

Nombre del fichero de la base de datos mágica, normalmente es algo como /path/to/magic.mime. Si no está especificada se utilizará la variable de entorno MAGIC. Si esta variable no está establecida, se utilizará /usr/share/misc/magic por defecto. Require la extensión .mime y/o .mgc.

Pasar NULL o una cadena vacía será el equivalente al valor por defecto.

Valores devueltos

(Sólo Estilo por procedimientos) Devuelve el recurso de la base de datos mágica si funciona o FALSE en caso de error.

Notas

Advertencia

A partir de PHP >= 5.3.11 y >= 5.4.1 el formato de base de datos mágico ha cambiado. A raíz de esto, los tipos mime internos de la base de datos han sido mejorados. Esto afecta especialmente al código donde se lee un fichero mágico externo. Leer ficheros mágicos con los formatos antiguos no funcionará. Además, algunas representaciones textuales de los tipos mime han cambiado, por ejemplo, para PHP sería devuelto "PHP script, ASCII text" en lugar de "PHP script text".

Ejemplos

Ejemplo #1 Estilo orientado a objetos

<?php
$finfo 
= new finfo(FILEINFO_MIME"/usr/share/misc/magic"); // Devuelve el tipo mime del tipo extensión

/* Obtiene el tipo mime para un fichero específico */
$filename "/usr/local/something.txt";
echo 
$finfo->file($filename);

?>

Ejemplo #2 Estilo por procedimientos

<?php
$finfo 
finfo_open(FILEINFO_MIME"/usr/share/misc/magic"); // Devuelve el tipo mime del tipo extensión

if (!$finfo) {
    echo 
"Ocurrió un error al intentar abrir la base de datos de fileinfo";
    exit();
}

/* Obtiene el tipo mime para un fichero específico */
$filename "/usr/local/something.txt";
echo 
finfo_file($finfo$filename);

/* cerrar conexión */
finfo_close($finfo);
?>

El resultado del ejemplo sería:

text/plain; charset=us-ascii

Ver también



finfo_set_flags> <finfo_file
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes finfo_open
illusivefingers at gmail dot com 06-Feb-2012 12:53
I am running Windows 7 with Apache.  It took hours to figure out why it was not working.

First, enable the php_fileinfo.dll extension in you php.ini. You'll also need the four magic files that are found in the following library:

http://sourceforge.net/projects/gnuwin32/files/file/4.23/file-4.23-bin.zip/download

An environment variable or a direct path to the file named "magic" is necessary, without any extension. 

Then, make sure that xdebug is either turned off or set the ini error_reporting to not display notices or warnings for the script.

Hope this saves someone a few hours of frustration!
olivier dot berger at it-sudparis dot eu 09-Mar-2011 12:02
On my Debian squeeze system, the path needed is like :
<?php
 $finfo
= new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
?>
franssen dot roland at gmail dot com 11-May-2010 12:23
Notice FileInfo::__construct() has strange behavior in PHP < 5.3.1 when a 2nd parameter is set explicitly, e.g.;

<?php
$fileInfo
= new finfo(FILEINFO_MIME, null);
?>

Expected result:
----------------
object(finfo)#2 (0) { }

Actual result:
--------------
Warning: finfo::finfo(): Failed to load magic database at ''. in *** on line ***
object(finfo)#2 (0) { }

See http://bugs.php.net/bug.php?id=51732
mark at dynom dot nl 09-Nov-2008 12:34
It seems there is quite some inconsistency in distributions and loading of magic files.

On Archlinux, the file is located here:
/usr/share/misc/file/magic.mgc

But this:

<?php
$fi
= new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic');
$fi->file('/tmp/fubar.txt');
?>

Actually segfaults, where if I type the full name (including the file extension:)

<?php
$fi
= new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic.mgc'); // added ".mgc"
$fi->file('/tmp/fubar.txt');
?>

It works as expected, so I guess something goes wrong with "A .mime and/or .mgc suffix is added if needed."
php at brudaswen dot de 15-Sep-2008 03:13
Since it costed me some time to find the needed magic database files for Windows, just a hint:

The last release of the GnuWin32 project with both needed files (magic and magic.mime) currently was "file-4.23".
All releases after 4.23 to 4.25-1 did not contain both needed files.

Hope that helps.
dario dot borreguero at gmail dot com 16-Apr-2008 03:15
Platform: WinXP-SP2, PHP5.2.5, MySQL 5.0, Apache 2.2.8

After reading former notes, I wasn't able to load my magic database: 'magic.mime' file (donwloaded from GnuWin32 project, zipped with the binary files v4.21). I always got an invalid $finfo object or finfo_open(...) returned FALSE.

In order to be able to load the 'magic.mime' file, Fileinfo library (bundled in PHP5.2.5) also requires 'magic' file.

For example:
1. Database:
  c:\php\magic.mime
  c:\php\magic

2. PHP Code:
<?php
  $filname
= 'c:\php\php.ini';
 
$finfo = new finfo(FILEINFO_MIME, 'c:\php\magic');
  if (!
$finfo) return false;
  echo
$finfo->file($filename);
?>

For further info see: http://pecl.php.net/bugs/bug.php?id=7555

Pay attention to comments added by 'christophe dot charron dot xul at gmail dot com'

NOTE: Before upgrading to PHP5.2.5, I was working with PHP5.2.1 and it only required 'magic.mime' file.
php at kingsquare dot nl 23-Jan-2008 07:41
The current version (1.04) doesnt support a different mime.magic database than the server default.

(the documentation is thus not correct)
Ubuntu default location is '/usr/share/file/magic'. In order for the examples to work all finfo_open()-commands must be issued with the extra location accordingly:
<?php
$file
= "/path/to/file.jpg";
$handle = finfo_open(FILEINFO_MIME, '/usr/share/file/magic');
$mime_type = finfo_file($handle,$file);
?>
ian at createanet dot co dot uk 02-Nov-2007 08:50
Couldn't get finfo to return the mimetype in the way expected so i made a function to do it with system()

<?php
function get_mime_type($filepath) {
   
ob_start();
   
system("file -i -b {$filepath}");
   
$output = ob_get_clean();
   
$output = explode("; ",$output);
    if (
is_array($output) ) {
       
$output = $output[0];
    }
    return
$output;
}
?>

hope it works for other people too
tularis at php dot net 06-May-2007 12:55
On Windows systems people might find that this always returns "application/x-dpkg".
There are 2 ways of solving this problem:
1. Get the mime-magic database file from GnuWin32 at <http://sourceforge.net/projects/gnuwin32/>
2. You can manually "fix" the mime-magic file by editing it and escaping all lines starting with !, thus changing each one to \!

 
show source | credits | stats | sitemap | contact | advertising | mirror sites