PHP tempnam() Function
The PHP tempnam() function creates a temporary file with a unique name in the specified directory, with access permission set to 0600. If the directory does not exist or is not writable, this function may generate a file in the system's temporary directory, and return the full path to that file, including its name.
Syntax
tempnam(directory, prefix)
Parameters
directory |
Required. Specify the directory where the temporary filename will be created. |
prefix |
Required. Specify the prefix of the generated temporary filename. |
Return Value
Returns the new temporary filename (with path), or false on failure.
Example:
In the example, a temporary file is created in the current directory. Then it is opened to write some content to it.
<?php //creating a temporary file $tempfile = tempnam("", "test"); if(!$tempfile) { echo "Unable to create a temporary file."; } else { echo "Temporary file name: ".$tempfile."\n"; //open the file with w+ mode $fp = fopen($tempfile, "w+"); //writing some content to the temporary file fwrite($fp, "Hello World!"); //set the file position to the start rewind($fp); //read and display the content echo fread($fp, 1024); //close the file fclose($fp); //delete the file unlink($tempfile); } ?>
The output of the above code will be:
Temporary file name: /tmp/testZ3ffir Hello World!
❮ PHP Filesystem Reference