Sunday, November 17, 2024
Google search engine
HomeLanguagesPHP tempnam() Function

PHP tempnam() Function

The tempnam() function is an inbuilt function in PHP that helps in creating a file having a unique file name by setting the access permission to 0600, having the specified directory. This function then generates the file in the system’s temporary directory, if the specified directory does not exist or is not writable. In that case, the full path to that specific file with its name will be returned.

Syntax:

tempnam(string $directory, string $prefix): string|false

Parameters:  This function accepts the following parameters:

  • directory: This parameter specifies the directory that contains the created temporary filename.
  • prefix: This parameter specifies the prefix of the generated temporary file name.

Return Value: The unique filename with a path will be returned otherwise returns “false” on failure.

Example 1: The following code demonstrates the PHP function tempnam() function.

PHP




<?php
  
$tmpfname = tempnam(
    "/home/dachman/Desktop/Articles/GFG/Method/", "work");
  
$handle = fopen($tmpfname, "w");
  
fwrite($handle, "writing to tempfile");
fclose($handle);
  
?>


Output: This creates a temporary file “work.txtOcB1ad” in the above directory, which when opened shows the following content.

writing to tempfile 

Example 2: This is another code example that demonstrates the PHP tempnam() function.

PHP




<?php
  
$tmpfname = tempnam(
    "/home/dachman/Desktop/Articles/GFG/Method/", "gfg");
      
if ($tmpfname) {
    echo "File is created with a unique name";
} else {
    echo "File is not created with a unique name";
}
  
?>


Output:

File is created with a unique name 

Reference: https://www.php.net/manual/en/function.tempnam.php

RELATED ARTICLES

Most Popular

Recent Comments