Backend Development 4 min read

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

This article explains how the PHP tmpfile() function creates a unique temporary file that is automatically deleted at script termination, demonstrates its syntax and usage with example code, and highlights important considerations such as resource handling and manual deletion with unlink().

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

In PHP programming, handling files is common, and sometimes a temporary file is needed for processing without permanent storage. The tmpfile() function creates such a temporary file with a unique name that is automatically removed when closed or when the script ends.

The function takes no parameters and returns a resource handle that can be used with standard file operations like fwrite() , fseek() , fread() , and fclose() .

Syntax:

resource tmpfile ( void )

Example usage:

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

The example shows creating a temporary file, writing a string, rewinding the pointer, reading the content, and finally closing the file, which also deletes it.

Note that the handle returned by tmpfile() is a resource type and can be stored in a variable (e.g., $file ) and passed to other file functions such as fwrite() , fseek() , and fclose() .

Additionally, while the temporary file is automatically removed at script termination, you can manually delete it at any time using the unlink() function if needed.

In summary, tmpfile() is a convenient PHP filesystem function for creating temporary files without specifying a name or path, useful for short‑lived operations, with automatic cleanup after the script finishes.

BackendPHPfile handlingtmpfiletemporary 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.