tmpfile() in PHP

By: Andi, Stig and Derick  

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:


$fp = tmpfile();

fwrite($fp, 'temporary data');



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:


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

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

fwrite($fp, 'temporary data');




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.

Archived Comments

Most Viewed Articles (in PHP )

Sorting an Array in PHP

Warning: session_start(): open .... failed - PHP error


PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/ into server:

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Function to return number of digits of an integer in PHP

Function to sort array by elements and count of element in PHP

Function to force strict boolean values in PHP

Function to convert strings to strict booleans in PHP

Convert IP address to integer and back to IP address in PHP

Latest Articles (in PHP)

Comment on this tutorial