PHP 檔案系統 tmpfile() 函式



PHP 檔案系統tmpfile() 函式用於在讀寫 (w+) 模式下建立具有唯一名稱的臨時檔案。此函式可以返回類似於 fopen() 函式為新檔案返回的檔案控制代碼,或者在失敗時返回 false。

當檔案關閉時(例如,透過呼叫 fclose() 函式或當沒有剩餘對 tmpfile() 函式返回的檔案控制代碼的引用時),或者當指令碼結束時,檔案將自動刪除。

語法

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

resource tmpfile ( void )

引數

tmpfile() 函式不接受任何引數。

返回值

該函式tmpfile() 在成功時返回類似於 fopen() 函式為新檔案返回的檔案控制代碼,在失敗時返回 FALSE。

注意事項

如果指令碼意外終止,則臨時檔案可能不會被刪除。

錯誤/異常

PHP stat() 函式在以下兩種情況下可能會給出錯誤和警告訊息:

  1. 指令碼結束或使用 fclose() 關閉時,臨時檔案會立即被刪除。
  2. tmpfile() 方法通常提供布林值 False,但通常返回一個計算結果為 False 的非布林值。

PHP 版本

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

示例

這是一個簡單的示例,向您展示如何使用 PHP 檔案系統tmpfile() 函式建立臨時檔案。

<?php
   $temp = tmpfile();
   fwrite($temp, "Tutorialspoint!!!!");
   rewind($temp);  // Rewind to start of a file
   echo fread($temp, 1024);  // Read 1k from a file

   fclose($temp);  // it removes the file
?>

輸出

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

Tutorialspoint!!!!

示例

以下是一個示例,演示如何在處理錯誤時使用tmpfile() 函式建立臨時檔案。

<?php
   $tempFile = tmpfile();

   if ($tempFile) {
      // Write to the temporary file
      fwrite($tempFile, "Hello, World!");

      // Move back to the beginning
      rewind($tempFile);

      // Read the content 
      echo fread($tempFile, 1024);

      // Close and delete the temporary file
      fclose($tempFile);
   } else {
      echo "Failed to create a temporary file.";
   }
?> 

輸出

這將產生以下結果:

Hello, World!

示例

以下是一個使用tmpfile() 函式生成和提供可下載檔案的示例。

<?php
   // Create a temporary file
   $tempFile = tmpfile();

   if ($tempFile) {
      // Generate some content
      $csvData = "Name,Email\nAmit Sharma,as@example.com\nVijay Chauhan,vc@example.com";

      // Write the CSV data 
      fwrite($tempFile, $csvData);

      // Set headers for a downloadable CSV file
      header('Content-Type: text/csv');
      header('Content-Disposition: attachment; filename="users.csv"');

      // Output the content of the temporary file
      rewind($tempFile);
      fpassthru($tempFile);

      // Close and delete the temporary file
      fclose($tempFile);
   } else {
      echo "Failed to create a temporary file.";
   }
?> 

輸出

這將生成以下輸出:

Name,Email
Amit Sharma,as@example.com
Vijay Chauhan,vc@example.com

示例

以下是一個使用tmpfile() 函式建立僅用於記錄資料的臨時檔案的示例。

<?php
   // Create a temporary file for logging data
   $tempFile = tmpfile();

   if ($tempFile) {
      // Log some data here
      $logMessage = date('Y-m-d H:i:s') . " - User logged in successfully.\n";

      // Write the log message 
      fwrite($tempFile, $logMessage);

      // Read and output the logged data
      rewind($tempFile);
      echo "Logged data:\n";
      echo fread($tempFile, 1024);

      // Close and delete the file
      fclose($tempFile);
   } else {
      echo "Failed to create a temporary file.";
   }
?> 

輸出

這將導致以下輸出:

Logged data:
2024-06-27 09:50:18 - User logged in successfully.

總結

tmpfile() 方法是用於建立臨時檔案的內建函式。此函式對於提供可下載檔案和臨時記錄資料非常有用。

php_function_reference.htm
廣告