PHP Tutorial - PHP tmpfile() Function






Definition

The tmpfile() function creates a temporary file with a unique name in read-write (w+) mode.

Syntax

PHP tmpfile() Function has the following syntax.

tmpfile()

Return

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

Note

The temporary file is automatically removed when it is closed with fclose(), or when the script ends.

Example

Create a temporary file and write and read


<?php
$temp = tmpfile();
fwrite($temp, "from java2s.com");
rewind($temp);//Rewind to the start of file
echo fread($temp,2048);//Read 2k from file
fclose($temp);//This removes the file
?>




Example 2

The following code shows how to creates a temporary file with a unique name in read-write (w+) mode.


  /*  w  w w .  ja v  a 2s  .  c om*/
<?php
    $temp = tmpfile();
    
    fwrite($temp, "Testing, testing.");
    //Rewind to the start of file
    rewind($temp);
    //Read 1k from file
    echo fread($temp,1024);
    
    //This removes the file
    fclose($temp);
?>

The code above generates the following result.