PHP.mk документација

finfo_open

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.finfo-open.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.finfo-open.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
finfo_open

Референца за `function.finfo-open.php` со подобрена типографија и навигација.

function.finfo-open.php

finfo_open

finfo::__construct

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

finfo_open -- finfo::__constructКреирај нова finfo инстанца

= NULL

Процедурален стил

finfo_open(int $flags = FILEINFO_NONE, ?string $magic_database = null): finfo|false

Обектно-ориентиран стил (конструктор):

public finfo::__construct(int $flags = FILEINFO_NONE, ?string $magic_database = null)

Оваа функција отвора база на податоци со магии и го враќа нејзиниот примерок.

Параметри

flags
Еден или дизјункција од повеќе Fileinfo константи.
magic_database
Име на датотека со база на податоци со магии, обично нешто како /path/to/magic.mime. Ако не е наведено, тогаш MAGIC променливата на околината се користи. Ако променливата на околината не е поставена, тогаш ќе се користи вклучената база на податоци со магии на PHP. Поминување null или празен стринг ќе биде еквивалентно на стандардната вредност.

Вратени вредности

(Само процедурален стил) Враќа finfo инстанца при успех, или false при неуспех.

Дневник на промени

Верзија = NULL
8.1.0 Враќа finfo инстанца сега; претходно, а resource .
8.0.3 magic_database сега е null.

Примери

Пример #1 Обектно-ориентиран стил

<?php
$finfo
= new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo
$finfo->file($filename);

?>

Пример #2 Процедурален стил

<?php
$finfo
= finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
echo
"Opening fileinfo database failed";
exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo
finfo_file($finfo, $filename);

/* close connection */
finfo_close($finfo);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

text/plain; charset=us-ascii

Белешки

Забелешка: Генерално, користењето на вклучената база на податоци со магии (со оставање на magic_database Пример #4 Споредување на вратената вредност на include MAGIC променливите на околината непоставени) е најдобриот курс на акција, освен ако конкретно не ви е потребна прилагодена база на податоци со магии.

Види Исто така

Белешки од корисници 9 белешки

illusivefingers at gmail dot com
пред 14 години
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!
dario dot borreguero at gmail dot com
пред 17 години
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.
Анонимен
12 години пред
For most common image files:
<?php
function minimime($fname) {
    $fh=fopen($fname,'rb');
    if ($fh) { 
        $bytes6=fread($fh,6);
        fclose($fh); 
        if ($bytes6===false) return false;
        if (substr($bytes6,0,3)=="\xff\xd8\xff") return 'image/jpeg';
        if ($bytes6=="\x89PNG\x0d\x0a") return 'image/png';
        if ($bytes6=="GIF87a" || $bytes6=="GIF89a") return 'image/gif';
        return 'application/octet-stream';
    }
    return false;
}
?>
olivier dot berger at it-sudparis dot eu
пред 15 години
On my Debian squeeze system, the path needed is like :
<?php 
 $finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
?>
php at brudaswen dot de
пред 17 години
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.
php at kingsquare dot nl
пред 18 години
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
пред 18 години
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
mark at dynom dot nl
пред 17 години
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 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
пред 18 години
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 \!
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.