tmpfile()
Introduction
In PHP, the tmpfile() function creates a temporary file and returns a file handle. This tutorial covers its syntax, behavior, and practical examples.
Understanding the tmpfile() Function
The tmpfile() function creates a temporary file with a unique name in the system's temporary directory and opens it for reading and writing (w+). It takes no parameters.
The file is created using the tmp:// stream wrapper. Important: The temporary file is automatically deleted when the file handle is closed or when the script ends, so no manual cleanup is required.
Syntax of the tmpfile() Function
The syntax of the tmpfile() function is as follows:
tmpfile(): resource|falseReturns a file handle on success, or false on failure.
Examples of Using tmpfile()
Let's take a look at an example of how the tmpfile() function can be used in PHP.
Example 1: Creating a Temporary File
<?php
$file_handle = tmpfile();
if ($file_handle === false) {
die('Failed to create temporary file');
}
fwrite($file_handle, 'Example data');
rewind($file_handle);
echo fread($file_handle, 1024);
fclose($file_handle);This example creates a temporary file using tmpfile(), checks for errors, writes data with fwrite(), reads it back with fread(), and closes the handle with fclose(). The file is automatically removed when fclose() is called.
Conclusion
The tmpfile() function provides a quick way to handle temporary data in PHP. Because the file is automatically removed when the handle is closed, it is ideal for short-term storage without manual cleanup.
Practice
What is the function of tmpfile() in PHP?