PHP - FileInfo finfo 類



PHP 的 finfo 類用於提供面向物件的介面到 fileinfo 函式。因此它有助於獲取有關檔案的資訊。

語法

以下是 PHP FileInfo finfo 類的語法:

finfo {
   public __construct([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] )
   public buffer( string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string
   public file( string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string
   public set_flags( int $options ) : bool
}

返回值

finfo 類為每個方法返回不同的值:

  • __construct() - 返回值為空。

  • buffer() - 返回字串,表示資料的型別,失敗則返回 false。

  • file() - 返回字串,表示檔案的型別,失敗則返回 false。

  • set_flags() - 成功返回 true,失敗返回 false。

PHP 版本

finfo 類首次引入於 PHP 5.3.0的核心版本中,在 PHP 7 和 PHP 8 中也能輕鬆執行。

示例 1

首先,我們將向您展示 PHP FileInfo finfo 類的基本示例,以獲取有關檔案或字串的資訊。

<?php
   /// Create a new finfo object
   $finfo = new finfo(FILEINFO_MIME_TYPE);
   
   // Analyze a file
   $fileType = $finfo->file('/PHP/PhpProjects/myfile.txt');
   echo "File type: $fileType\n";
   
   // Analyze a string
   $stringType = $finfo->buffer('Hello, world!');
   echo "String type: $stringType";
   
   // Set new flags
   $finfo->set_flags(FILEINFO_NONE);
?>

輸出

以下是以下程式碼的結果:

File type: text/plain
String type: text/plain

示例 2

在下面的 PHP 程式碼中,我們將嘗試使用 finfo 類來獲取檔案的 MIME 型別。

<?php
   // Create a new finfo object 
   $finfo = new finfo(FILEINFO_MIME_TYPE);
   
   // Get the MIME type of a file
   $fileType = $finfo->file('/PHP/PhpProjects/document.pdf');
   echo "File type: $fileType"; 
?> 

輸出

這將生成以下輸出:

File type: application/pdf

示例 3

現在,以下程式碼使用 MIME 編碼標誌建立一個新的 finfo 物件後,使用 finfo 類獲取檔案的 MIME 編碼。

<?php
   // Create a new finfo object
   $finfo = new finfo(FILEINFO_MIME_ENCODING);
   
   // Get the MIME encoding of a file
   $fileEncoding = $finfo->file('/PHP/PhpProjects/example.txt');
   echo "File encoding: $fileEncoding"; 
?> 

輸出

這將建立以下輸出:

File encoding: us-ascii

示例 4

在以下示例中,我們使用 finfo 函式分析字串的 MIME 型別。

<?php
   // Create a new finfo object
   $finfo = new finfo(FILEINFO_MIME_TYPE);
   
   // Analyze a string
   $string = "Hello, world!";
   $stringType = $finfo->buffer($string);
   echo "String type: $stringType"; 
?> 

輸出

以下是上述程式碼的輸出:

String type: text/plain

總結

以上示例展示了使用 finfo 類檢查檔案型別、檔案編碼和字串型別的不同方法。

php_function_reference.htm
廣告