PHP Function Reference

PHP tmpfile() Function



The PHP tmpfile() function creates and opens a temporary file with a filename guaranteed to be different from any other existing file. The file is opened in read-write (w+) mode and returns a file handle.

If the script closes the file, e.g. by calling fclose(), the file is automatically deleted. If the script ends normally, all files opened by calling tmpfile() are also automatically deleted.

Note: If the script terminates unexpectedly, the temporary file may not be deleted.

Syntax

tmpfile()

Parameters

No parameter is required.

Return Value

Returns a file handle, similar to the one returned by fopen(), for the new file or false on failure.

Example:

The example below demonstrates on using this function to create a temporary file and write some content to it.

<?php
//creating a temporary file
$temp = tmpfile();

if(!$temp) {
  echo "Unable to create a temporary file.";
} else {
  //writing some content to the temporary file
  fwrite($temp, "Hello World!");
  
  //set the file position to the start
  rewind($temp);
  
  //read and display the content
  echo fread($temp, 1024);

  //close the file - this will delete the file
  fclose($temp); 
}
?>

The output of the above code will be:

Hello World!

❮ PHP Filesystem Reference