[Danny Berger](https://dpb587.me/ "Home")

# Path-based tmpfile in PHP

March 5, 2013

PHP has the [`tmpfile`](http://php.net/manual/en/function.tmpfile.php) function for creating a file handle which will automatically be destroyed when it is closed or when the script ends. PHP also has the [`tempnam`](http://php.net/manual/en/function.tempnam.php) function which takes care of creating the file and returning the path, but doesn't automatically destroy the file.

To get the best of both worlds (temp file + auto-destroy), I have found this useful:

```
function tmpfilepath() {
    $path = stream_get_meta_data(tmpfile())['uri'];

    register_shutdown_function(
        function () use ($path) {
            unlink($path);
        }
    );

    return $path;
}
```

## Reader Comments

Copyright © 2026 // [dpb587.me](https://dpb587.me/) is a [personal](https://dpb587.me/projects/website), [open source](https://github.com/dpb587/dpb587.me/blob/main/content/post/2013/path-based-tmpfile-in-php-20130305.md) site.
