Using PHP tmpfile() to Create and Manage Temporary Files
This article explains how the PHP tmpfile() function creates a unique temporary file that is automatically removed at script termination, demonstrates its syntax, shows a complete example with fwrite, fseek, fread and fclose, and highlights important usage considerations such as manual deletion with unlink().
In PHP programming, handling files is common, and sometimes a temporary file is needed without persisting it. The tmpfile() function creates a uniquely named temporary file that is automatically deleted when closed or when the script ends, freeing disk space.
The function has no parameters and returns a resource handle that can be used with standard file operations. Its syntax is:
resource tmpfile ( void )A simple example demonstrates creating a temporary file, writing data, rewinding, reading, and finally closing the file:
<?php
$file = tmpfile(); // create a temporary file
if ($file) {
fwrite($file, 'Hello, World!'); // write data
fseek($file, 0); // rewind to start
echo fread($file, filesize($file)); // read and output
fclose($file); // close and delete
}
?>In this example, tmpfile() returns a resource stored in $file . The handle is then used with fwrite() , fseek() , fread() , and fclose() to manipulate the temporary file.
Note that the handle is a resource type, so it can be passed to any other file‑handling functions such as fwrite() , fseek() , and fclose() . The temporary file is automatically removed when the script finishes, but if manual removal is desired at any point, the unlink() function can be used.
In summary, tmpfile() is a convenient PHP filesystem function for creating temporary files without needing to specify a name or path, allowing short‑lived file operations that are automatically cleaned up after execution.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.