tmpfile() in PHP

By: Andi, Stig and Derick Printer Friendly Format    


In case you want to create a temporary file, the best way to do it is with the tmpfile() function. This function creates a temporary file with a unique random name in the current directory and opens this file for writing. This temporary file will be closed automatically when you close the file with fclose() or when the script ends:

<?php

$fp = tmpfile();

fwrite($fp, 'temporary data');

fclose(fp);

?>

In case you want to have more control over where the temporary file is created and about its name, you can use the tempnam() function. On the contrary to the tmpfile() function, this file will not be removed automatically:

<?php

$filename = tempnam('/tmp', 'p5pp');

$fp = fopen($filename, 'w');

fwrite($fp, 'temporary data');

fclose(fp);

unlink($filename);

?>

The first parameter to the function specifies the directory where the temporary file is created, and the second parameter is the prefix that will be added to the random file name.



Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial