256 of 410 menu

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

tmpfile();

Example

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

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

Code execution result:

'test data'

Example

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

<?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:

'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
byenru