Summary: in this tutorial, you will learn how to use the PHP tmpfile()
and tempnam()
functions to create a temporary file.
Introduction to the temp file
A temporary file only exists during the execution of the script. It means that PHP automatically deletes the temporary file when the script ends.
To create a temporary file, you use the tmpfile()
function:
tmpfile ( ) : resource|false
Code language: JavaScript (javascript)
The tmpfile()
function creates a temporary file in a read/write (w+
) mode. The tmpfile()
function returns the filehandle. If the function fails to create the file, it returns false
.
Note that the tmpfile()
function creates a temporary file with a unique name.
In fact, PHP automatically deletes the temporary file created by the tmpfile()
function:
- When you close the file by calling the
fclose()
function. - When the file handle doesn’t have any references.
- or when the script ends.
PHP tmpfile() function example
The following example uses the tmpfile()
function to create a new temporary file and write a text to it:
<?php
$f = tmpfile();
if (false !== $f) {
// write some text to the file
fputs($f, 'The current time is ' . strftime('%c'));
}
echo 'The current time is ' . strftime('%c');
exit(1);
Code language: HTML, XML (xml)
How it works.
- First, create a new temporary file using the
tmpfile()
function. - Second, write a string to the file using the
fputs()
function.
The tempnam() function
The tempnam()
function creates a temporary file in a directory and returns the full path to the temporary file:
tempnam ( string $directory , string $prefix ) : string|false
Code language: PHP (php)
The tempnam()
function has two parameters.
$directory
is the directory of the temporary file. If the directory doesn’t exist or isn’t writable, thetempnam()
creates the temporary file in the system temporary directory specified by theTMPDIR
environment variable on Unix or theTMP
environment variable on Windows.$prefix
is the prefix of the temporary file name.
The following example shows how to use the tempnam()
function to create a temporary file in the tmp
directory:
<?php
$name = tempnam('tmp', 'php');
// full path to the temp file
echo $name; //C:\xampp\htdocs\tmp\phpA125.tmp
// open the temporary file
$f = fopen($name, 'w+');
if ($f) {
// write a text to the file
fputs($f, 'the current time is ' . strftime('%c'));
fclose($f);
}
Code language: HTML, XML (xml)
In this example, if you pass an empty string to the directory, the tempnam()
function will create the temporary file in the system temporary directory e.g., on Windows, it is: C:\Users\<username>\AppData\Local\Temp\php778.tmp
Summary
- Use the
tmpfile()
function to create a temporary file that exists only during the execution of the script. - Use the
tmpname()
function to create a temporary file in a directory and return the full path of the file.