The tmpfile Function

The tmpfile function creates a temporary file with a unique name and returns a file pointer to it. The file is opened in read and write mode (w+). When the file is closed or the script terminates, the temporary file is automatically deleted.

Syntax

phptmpfile();

Example

Let's create a temporary file and write a string to it:

php<?php
  $tmp = tmpfile();
  fwrite($tmp, 'test data');
  rewind($tmp);
  echo fread($tmp, 1024);
  fclose($tmp);
?>

Code execution result:

php'test data'

Example

Let's check that the file is automatically deleted after closing:

php<?php
  $tmp = tmpfile();
  $meta = stream_get_meta_data($tmp);
  echo file_exists($meta['uri']) ? 'Exists' : 'Deleted';
  fclose($tmp);
  echo file_exists($meta['uri']) ? 'Exists' : 'Deleted';
?>

Code execution result:

php'ExistsDeleted'

See Also

  • the tempnam function,
    which creates a file with a unique name
  • the fopen function,
    which opens a file
  • the fclose function,
    which closes a file