How to Use PHP’s tmpfile() to Create and Manage Temporary Files
Learn how PHP’s tmpfile() function creates unique temporary files that are automatically removed, explore its syntax, see a full example with reading and writing operations, and understand important considerations such as resource handling and manual deletion with unlink().
In PHP programming, handling files is common, and sometimes you need a temporary file without keeping it long‑term; the tmpfile() function creates such a file.
The tmpfile() function is a PHP filesystem function that creates a uniquely named temporary file, which is automatically deleted when closed or when the script ends, so it does not occupy persistent disk space. resource tmpfile ( void ) The function takes no parameters and returns a temporary file handle that can be used for reading and writing.
Example:
<?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 the temporary file
}
?>In the example, tmpfile() creates a temporary file stored in $file. fwrite() writes a string, fseek() moves the pointer to the beginning, fread() reads the data, and fclose() closes and removes the file.
Note that the handle returned by tmpfile() is a resource type, which can be used with other file functions such as fwrite(), fseek(), and fclose().
Additionally, the temporary file is automatically deleted when the script finishes; if you need to delete it manually at any time, you can call unlink().
In summary, tmpfile() is a convenient PHP filesystem function for creating temporary files without specifying a name or path, useful for short‑lived operations, but remember the file only exists during script execution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
