In PHP, tempnam() creates a new empty file with a unique name in a folder you choose and returns the full path.
It is a safe way to get a temporary file because PHP makes sure the name is not used yet. The file is created for you, but it is not deleted automatically, so you remove it with unlink() when you are done.
Syntax
Call tempnam() with the values you need. Start with this line.
PHP
$file = tempnam(sys_get_temp_dir(), 'demo');
Call
What it does
tempnam(sys_get_temp_dir(), 'demo')
Creates a file such as /tmp/demoA1b2C3 in the system temp folder.
tempnam(__DIR__ . '/cache', 'tmp_')
Creates a temporary file inside your own cache folder.
tempnam('/no/such/folder', 'x')
Falls back to the system temp folder if the folder does not exist.
The file is created with permissions 0600, so only the owner can read and write it. The prefix is limited to a few characters on some systems. Use sys_get_temp_dir() to find the right temp folder on any server.
Name starts with demo
File exists: yes
Size: 0 bytes
How It Works
tempnam() creates an empty file with a unique name that begins with demo.
basename() removes the folder part so we can test the start of the name.
The file already exists on disk but has no content yet, so its size is 0.
unlink() deletes the file because PHP does not do it for you.
Example 2 — A Folder That Does Not Exist
When the folder is missing, tempnam() uses the system temp folder instead of failing.
PHP
<?php
$file = @tempnam('/no/such/folder', 'demo');
if ($file === false) {
echo 'Could not create a file', PHP_EOL;
} elseif (dirname($file) === rtrim(sys_get_temp_dir(), '/\\')) {
echo 'Fell back to the system temp folder', PHP_EOL;
unlink($file);
}
Output
Fell back to the system temp folder
How It Works
The folder /no/such/folder does not exist.
tempnam() quietly uses the system temp folder instead, and @ hides the notice PHP raises.
dirname() gives the folder of the new file, which we compare with sys_get_temp_dir().
Because they match, the script prints the fallback message and deletes the file.
Example 3 — Write, Read and Clean Up
Use a temporary file to hold data for a moment, then remove it. Two calls also give two different names.