PHP 檔案系統 tempnam() 函式



PHP 檔案系統tempnam()函式用於在指定的目錄中建立一個具有唯一檔名 的臨時檔案,它可以返回新的臨時檔名(包含路徑),或者在失敗時返回false。

此函式可以建立一個具有唯一檔名的檔案,其訪問許可權在指定的目錄中設定為 0600。如果目錄不存在或不可寫,tempnam() 函式能夠在系統的臨時目錄中生成一個檔案,並返回包含其名稱的該檔案的完整路徑。

語法

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

string tempnam ( string $dir, string $prefix )

引數

以下是tempnam()函式的必需和可選引數:

序號 引數及說明
1

$dir(必需)

這是將建立臨時檔案的目錄。

2

$prefix(必需)

這是檔名的字首。

返回值

tempnam()函式成功時返回包含路徑的新臨時檔名,失敗時返回 FALSE。

PHP 版本

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

示例

這是一個簡單的示例,演示如何使用 PHP 檔案系統tempnam()函式在給定目錄中建立臨時檔案。

<?php
   echo tempnam("C:\PhpProject", "TEMP0");
?>

輸出

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

C:\PhpProject\TMPABFA.tmp

示例

這是一個額外的示例,演示如何使用tempnam()函式在給定目錄中建立臨時檔案。

<?php
   // Path to the directory
   $dir = "C:\PhpProject"; 
   $prefix = "TEMPORARY";
   $tempfilename = tempnam($dir, $prefix); 
   
   $handle = fopen($tempfilename, "w"); 
   
   fwrite($handle, "writing to tempfile"); 
   fclose($handle); 

   echo "Temporary file has been created successfully! :" . $tempfilename;
?> 

輸出

這將產生以下結果:

Temporary file has been created successfully! : C:\PhpProject\TEMPORARYLgNr9K.tmp

示例

這是用於使用tempnam()函式在系統的預設臨時目錄中建立臨時檔案的 PHP 程式碼,其名稱以“prefix_”開頭。

<?php
   $temp_file = tempnam(sys_get_temp_dir(), 'prefix_');
   if ($temp_file) {
      echo "Temporary file created: " . $temp_file;
   } else {
      echo "Failed to create temporary file.";
   }
?> 

輸出

這將生成以下輸出:

Temporary file created: /private/var/folders/92/7wtrqd0j3q95q0_1z2qkl79h0000gn/T/prefix_E2pUqG

示例

在此示例中,我們將使用tempnam()函式建立一個臨時檔案,但如果在檔案建立過程中發生任何錯誤,我們也會處理該錯誤。

<?php
   // Mention the directory 
   $directory = '/tmp';

   // Mention a prefix
   $prefix = 'example_';

   // Create the temporary file
   $temp_file = tempnam($directory, $prefix);

   // Check if the file was created successfully
   if ($temp_file) {
      echo "Temporary file created: " . $temp_file . "\n";
      // Write some data to the temporary file
      file_put_contents($temp_file, "This is some temporary data.");
      echo "Data written to temporary file.\n";
   } else {
      echo "Failed to create temporary file.";
   }
?> 

輸出

這將導致以下輸出:

如果成功建立檔案:

Temporary file created: /PhpProjects/example_nI6sX1
Data written to temporary file.

如果建立檔案失敗:

Failed to create temporary file.

總結

tempnam()方法是 PHP 中用於建立臨時檔案的內建函式。它對於建立臨時檔案以臨時儲存資料非常有用,並且它還確保唯一的檔名以避免衝突。

php_function_reference.htm
廣告