PHP 檔案系統 filesize() 函式



PHP 檔案系統filesize()函式用於獲取檔案的位元組大小。在接收檔案路徑作為輸入後,它將以整數形式返回檔案大小(以位元組為單位)。

當您需要在對檔案進行任何更改之前確認檔案的大小,此工具很有用。例如,您可以在進一步處理上傳的檔案之前,使用它來確保上傳的檔案大小不超過限制。

語法

以下是 PHP 檔案系統filesize()函式的語法:

int filesize ( string $filename )

引數

下面提到了使用filesize()函式所需的的引數:

序號 引數及描述
1

filename(必填)

將用於獲取大小的檔案。

返回值

此函式可以返回檔案的大小(以位元組為單位),或者在發生錯誤時返回 false(並可能生成 E_WARNING 級別的錯誤)。失敗時返回 FALSE。

PHP 版本

filesize()函式最初作為核心 PHP 4 的一部分引入,並且與 PHP 5、PHP 7、PHP 8 相容。

示例

下面的 PHP 程式碼用於在 PHP 檔案系統filesize()函式的幫助下獲取指定檔案路徑的檔案大小,它將以位元組為單位返回大小。

<?php
   //Path to the file to be used
   $filename = "/PhpProject/sample.txt";
   echo $filename . ': ' . filesize($filename) . ' bytes';
?>

輸出

這將產生以下結果:

/PhpProject/sample.txt: 27 bytes

示例

下面的 PHP 示例向我們展示瞭如何使用filesize()來檢查目錄中多個檔案的大小。因此,為了獲取目錄中的檔案列表,我們將使用 scandir() 函式。

<?php
   // Define the directory path 
   $directory = "/Applications/XAMPP/xamppfiles/htdoc/mac";
   $totalSize = 0;
   $files = scandir($directory);
   foreach ($files as $file) {
      if ($file !== '.' && $file !== '..') {
            $filePath = $directory . '/' . $file;
            $totalSize += filesize($filePath);
      }
   }
   echo "Total size of files in directory: " . $totalSize . " bytes";
?> 

輸出

這將生成以下結果:

Total size of files in directory: 164 bytes

示例

此 PHP 示例向我們展示瞭如何使用filesize()函式來限制上傳到網站的檔案的大小。

<?php
   $maxFileSize = 5 * 1024 * 1024; // 5 MB
   if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
      if (filesize($_FILES['file']['tmp_name']) <= $maxFileSize) {
         // Process the uploaded file
      } else {
         echo "Error: File size exceeds the allowed limit.";
      }
   } else {
      echo "Error uploading file.";
   }
?> 

輸出

這將建立以下結果:

# If the uploaded file size is within the permitted limit, the function will run the file.
# If the uploaded file size exceeds what is permitted, this message will show up: "Error: File size exceeds the allowed limit."
# If there is an issue with the file upload, this message will show up: "Error uploading file."

示例

在下面的 PHP 程式碼示例中,我們將看到如何在filesize()函式的幫助下監視伺服器上的磁碟空間使用情況。

<?php
   $directories = array("/var/www/html", "/home/user/uploads");
   $totalDiskSpaceUsed = 0;
   foreach ($directories as $dir) {
      $files = scandir($dir);
      foreach ($files as $file) {
         if ($file !== '.' && $file !== '..') {
               $filePath = $dir . '/' . $file;
               $totalDiskSpaceUsed += filesize($filePath);
         }
      }
   }
   echo "Total disk space used: " . $totalDiskSpaceUsed . " bytes";
?> 

輸出

這將導致以下結果:

Total disk space used: 1680 bytes

總結

PHP 方法filesize()返回檔案的大小(以位元組為單位)。它以檔案路徑作為引數,並以整數形式返回檔案大小(以位元組為單位)。我們在本章中看到的示例演示瞭如何在應用程式(如檔案大小檢查)中使用 PHP 的filesize()函式。

php_function_reference.htm
廣告