W3docs

tmpfile()

In PHP, the tmpfile() function is used to create a temporary file. It is a useful function for working with files in your PHP scripts. In this article, we will

Introduction

When a PHP script needs a place to stash data that only matters for the duration of that request — a buffer too big to keep in memory, a CSV you're about to stream to the browser, output captured from an external command — you reach for a temporary file. The tmpfile() function gives you one with a single call: it creates a unique file in the system temp directory, opens it for reading and writing, and hands back a file handle. Best of all, it cleans up after itself.

This chapter covers the syntax, the auto-cleanup behavior that makes tmpfile() special, when to use it versus tempnam(), and several runnable examples including a few common gotchas.

What Is a Temporary File?

A temporary file is a file your program uses as scratch space and does not intend to keep. It lives in the operating system's temporary directory (/tmp on Linux/macOS, C:\Windows\Temp or the path in the TEMP environment variable on Windows). Because many processes share that directory, temp files need unique names so two scripts don't clobber each other — tmpfile() handles that uniqueness for you.

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 in w+ mode (the file starts empty, and you can both write to it and read it back). It takes no parameters.

The key feature is automatic cleanup. The temporary file is removed when:

  • you close the handle with fclose(), or
  • the script finishes and the handle goes out of scope.

Because of this, you almost never need to delete the file yourself. The trade-off is that tmpfile() does not tell you the file's path — the handle is the only reference you get. If you need a known filename you can pass to another program, use tempnam() instead.

Syntax of the tmpfile() Function

The syntax of the tmpfile() function is as follows:

tmpfile(): resource|false

The function takes no arguments and returns:

  • a file handle (resource) positioned at the start of the empty file on success, or
  • false on failure — for example, when the temp directory is not writable.

Always check the return value before using the handle, because passing false to functions like fwrite() triggers a TypeError on PHP 8+.

Examples of Using tmpfile()

Example 1: Write, Read Back, and Auto-Cleanup

The most common pattern: open a temp file, write to it, rewind the pointer, and read it back. Note the rewind() call — after writing, the internal pointer sits at the end of the data, so without rewinding fread() would return an empty string.

<?php

$handle = tmpfile();
if ($handle === false) {
    die('Failed to create temporary file');
}

fwrite($handle, 'Example data');
rewind($handle);                  // move pointer back to the beginning
echo fread($handle, 1024);        // read up to 1024 bytes
fclose($handle);                  // closing also deletes the file

Output:

Example data

The file is removed the moment fclose() runs, so there is nothing to clean up manually.

Example 2: Finding the Temp File's Real Path

Although tmpfile() hides the filename, you can recover it through the stream's metadata with stream_get_meta_data(). This is handy for logging or debugging — for instance, to confirm the file really disappears.

<?php

$handle = tmpfile();
$meta   = stream_get_meta_data($handle);
$path   = $meta['uri'];

echo 'Temp file exists before close: ';
echo file_exists($path) ? 'yes' : 'no';
echo "\n";

fclose($handle);

echo 'Temp file exists after close:  ';
echo file_exists($path) ? 'yes' : 'no';
echo "\n";

Output:

Temp file exists before close: yes
Temp file exists after close:  no

Example 3: Buffering CSV Rows Before Sending

A realistic use case: build a CSV in a temp file using fputcsv(), then read the whole thing back to return or stream it. This keeps large data out of memory while still letting you assemble it line by line.

<?php

$rows = [
    ['Name', 'Role'],
    ['Ada', 'Engineer'],
    ['Linus', 'Maintainer'],
];

$handle = tmpfile();
foreach ($rows as $row) {
    fputcsv($handle, $row);
}

rewind($handle);
echo stream_get_contents($handle);   // read everything from the pointer to EOF
fclose($handle);

Output:

Name,Role
Ada,Engineer
Linus,Maintainer

tmpfile() vs tempnam()

Both create temporary files, but they solve different problems:

Aspecttmpfile()tempnam()
ReturnsAn open file handleA filename (string)
Opens the file?Yes (w+)No — you call fopen() yourself
Auto-deletes?Yes, on close / script endNo — you must unlink() it
You know the path?Only via stream_get_meta_data()Yes, directly

Rule of thumb: use tmpfile() for self-contained scratch data within one script; use tempnam() when you need a named file to hand to another process or to keep after the request.

Common Pitfalls

  • Forgetting to rewind(). After writing, the pointer is at the end. Reading without rewinding returns nothing.
  • Assuming a return value. On a read-only temp directory tmpfile() returns false; always guard against it.
  • Expecting the file to persist. Once the handle closes, the file is gone — copy the data out (with fopen() to a permanent path, file_put_contents(), etc.) if you need to keep it.

Conclusion

The tmpfile() function is the simplest way to get a private, auto-cleaning scratch file in PHP. It hands you a read-write handle, places the file safely in the system temp directory, and deletes it the moment you close the handle or the script ends — no manual housekeeping required. Reach for it whenever you need short-lived storage and don't care about the filename; reach for tempnam() when you do.

Practice

Practice
What is the function of tmpfile() in PHP?
What is the function of tmpfile() in PHP?
Was this page helpful?