Table of Contents

Request for Comments: Modify tempnam() to handle directories and auto-cleanup

Introduction

This RFC recommends a set of changes to the tempnam() standard function.

  1. Extend the signature to include an “options” parameter (default keeping current behavior).
  2. Define TEMPNAM_DIR constant which, when passed to options, creates a directory instead of a file.
  3. Define TEMPNAM_REQUEST constant which, when passed to options, automatically removes the file/directory at the end of the request.

TEMPNAM_REQUEST

It's a common bug to forget to remove temporary files and after a period of time these may overpopulate the filesystem. TEMPNAM_REQUEST seeks to avoid this by building a mechanism to automatically clean up after scripts.

$fn = tempnam("/tmp/", "test-", TEMPNAM_REQUEST);
file_put_contents($fn, "This is some data");
echo shell_exec("/usr/bin/someprog " . escapeshellarg($fn));
// No need to explicitly unlink($fn), since it will be cleaned up at request end

TEMPNAM_DIR

TEMPNAM_DIR expands the scope and usability of this function to whole directories of files while keeping the number of entities which need to be tracked low.

$file = tempnam("/tmp/", "", TEMPNAM_REQUEST);
copy('http://www.php.net/get/php-5.4.9.tar.gz/from/us3.php.net/mirror', $file);

$dir  = tempnam("/tmp/", "", TEMPNAM_DIR | TEMPNAM_REQUEST);
$dir  = escapeshellarg($dir);
$file = escapeshellarg($file);
shell_exec("cd $dir && tar -zxf $file");
// tarball expanded into dir, both will be removed at request end

tmpfile()

Although the existing function tmpfile() provides for the TEMPNAM_REQUEST cleanup functionality, it does not provide an actual filename which can be passed to external programs.

Implementation

Other Options

Proposal and Patch

Coming soon, giving a chance to start discussion early.