Backend Development 4 min read

Using PHP's tmpfile() Function to Create and Manage Temporary Files

This article explains how PHP's tmpfile() function creates a unique temporary file that is automatically deleted when closed or when the script ends, and demonstrates its usage with example code for writing, reading, and cleaning up the file.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's tmpfile() Function to Create and Manage Temporary Files

In PHP programming, handling files is a common operation, and sometimes a temporary file is needed without persisting it; the tmpfile() function provides a convenient way to create such a file.

The tmpfile() function is a PHP filesystem function that creates a uniquely named temporary file; the file is automatically removed when the handle is closed or when the script terminates, so it does not occupy permanent disk space.

Syntax:

resource tmpfile ( void )

The function takes no parameters and returns a temporary file handle that can be used for read/write operations.

Below is a simple example demonstrating how to create a temporary file with tmpfile() , write data to it, rewind the pointer, read the data back, and finally close the file, which also deletes it:

<?php
$file = tmpfile(); // create a temporary file
if ($file) {
    fwrite($file, 'Hello, World!'); // write data
    fseek($file, 0); // rewind to the beginning
    echo fread($file, filesize($file)); // read and output data
    fclose($file); // close and delete the temporary file
}
?>

In the example, tmpfile() creates the temporary file handle $file . The fwrite() function writes a string into the file, fseek() moves the file pointer back to the start, and fread() reads the content for output. Finally, fclose() closes and removes the temporary file.

Note that the handle returned by tmpfile() is a resource type, which can be used with other file‑operation functions such as fwrite() , fseek() , and fclose() .

Additionally, the temporary file created by tmpfile() is automatically deleted when the script ends; if manual deletion is required 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 temporary operations without worrying about cleanup, as the file exists only during script execution.

Backendfile handlingphp tutorialtmpfiletemporary file
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.