tempnam

(PHP 3, PHP 4, PHP 5)

tempnam -- 建立一个具有唯一文件名的文件

说明

string tempnam ( string dir, string prefix )

在指定目录中建立一个具有唯一文件名的文件。如果该目录不存在,tempnam() 会在系统临时目录中生成一个文件,并返回其文件名。

在 PHP 4.0.6 之前,tempnam() 函数的行为取决于系统。在 Windows 下 TMP 环境变量会越过 dir 参数,在 Linux 下 TMPDIR 环境变量优先,而在 SVR4 下总是使用 dir 参数,如果其指向的目录存在的话。如果有疑问请参考系统文档中的 tempnam(3) 函数。

注: 如果 PHP 不能在指定的 dir 参数中创建文件,则退回到系统默认值。

返回新的临时文件名,出错返回 FALSE

例子 1. tempnam() 例子

<?php
$tmpfname
= tempnam("/tmp", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);
// do here something
unlink($tmpfname);
?>

注: 本函数的行为在 4.0.3 版中改变了。也会建立一个临时文件以避免竞争情形,即有可能会在产生出作为文件名的字符串与脚本真正建立该文件之间会在文件系统中存在同名文件。注意,如果不再需要该文件则要删除此文件,不会自动删除的。

参见 tmpfile()unlink()


add a note add a note User Contributed Notes
tux ARROBA cenobioracing PUNTO com
28-Aug-2006 08:19
Beware that on Windows NT and other windows, if you have, for example, a variable $work_dir with a path to some dir on your document root(or any other dir). Note the following:
<?php
$work_dir
= 'C:/some/path/to/document_root/dir';
file_exists($working_dir); // Returns true
is_writable($working_dir); // Returns true
$tempfile = tempnam($working_dir,'img');
//$temfile now contains a system wide temp directory file, like 'C:/WINNT.SBS/img444.tmp' instead of the directory we pass it
//Thats because we need to give I_USR (IIS user) user write permission to $working_dir  although according to the aforementioned functions seemed it already had it...
//If you want to use just the system wide temp directory return by default by tempnam you will also need to give it write permission to I_USR user to be able to write to that file...
?>
Guillaume Paramelle
06-Jun-2006 09:46
On a windows server (php 5.1.2), tempnam() may not use the dir parameter, and create the file in $_ENV['TMP'].
I also had problem because the directory was relative.
Everything was solved using :

tempnam(realpath("../_cache/"), "prefix") ;
Ron Korving
03-Feb-2006 04:32
This function creates a temporary directory. The previous example given could bug if between the unlink() and mkdir() some process creates the same directory or file. This implementation is faster too.

<?php
 
function tempdir($dir, $prefix='', $mode=0700)
  {
   if (
substr($dir, -1) != '/') $dir .= '/';

   do
   {
    
$path = $dir.$prefix.mt_rand(0, 9999999);
   } while (!
mkdir($path, $mode));

   return
$path;
  }
?>
KOmaSHOOTER at gmx dot de
19-Sep-2005 04:51
This Example makes a File called "user.txt"
in the dir www.XXXXX.XX/restricted/
<?php
$tmpfname
= tempnam($_ENV["DOCUMENT_ROOT"]."/restricted", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something
//echo($_ENV["DOCUMENT_ROOT"]);
copy($tmpfname,'user.txt');
 
?>
chris
14-Jun-2005 12:23
Use the following to create a temporary directory...

// Creates a directory with a unique name
// at the specified with the specified prefix.
// Returns directory name on success, false otherwise
function tmpdir($path, $prefix)
{
       // Use PHP's tmpfile function to create a temporary
       // directory name. Delete the file and keep the name.
       $tempname = tempnam($path,$prefix);
       if (!$tempname)
               return false;

       if (!unlink($tempname))
               return false;

       // Create the temporary directory and returns its name.
       if (mkdir($tempname))
               return $tempname;

       return false;
}
php at REMOVEMEkennel17 dot co dot uk
06-Mar-2005 02:10
Note that tempnam returns the full path to the temporary file, not just the filename.
17-Feb-2005 10:13
Regarding Typo3 and Safe mode "Generally, everything in TYPO3 can work under safe_mode and open_basedir as long as the script permissions are correct. Notice, this is not something TYPO3 can do better or worse; for a working TYPO3 system there must be access to writing files and directories in the filesystem and this is done by plain PHP functions."
Sebastian Kun
22-Jan-2005 05:03
If you go to the linux man page for the C function tempnam(3), you will see at the end "Never use this function. Use mkstemp(3) instead." But php's tempnam() function doesn't actually use tmpnam(3), so there's no problem (under Linux, it will use mkstemp(3) if it's available).
Nick Smith
21-Jan-2005 03:35
It is worth noting that if the 'dir' that you supply doesn't exist, then it is silently ignored and the system /tmp directory used. At least under Linux, PHP v4.1.2.

I had a script that appeared to work fine with safe mode switched off, but I didn't realise that my 'dir' parameter had a typo (so the files were going in /tmp), and once safe mode was switched on I started getting errors because the rest of the script couldn't read files from the system /tmp folder.
soletan at toxa dot de
03-Dec-2004 12:45
tempnam and SAFE MODE don't generally exclude each other - that link below just shows frustrating trials to find some meaning in SAFE MODE. However, SAFE MODE is good and I'd appreciate to find it used in more of contemporarily hyped projects like typo3 or similar, since many people don't seem to care about security that much, but get enraged by tens and hundreds of Spam-Mails a day.

Okay, that post from Feb-2004 and the "bug report" is unconditionally true for multi-hosted PHP environments where several users may have their individual scripts placed on same server machine. Just take a visit to one of your local webspace-providers, that give space for 5  or less a month.

But the truth get conditional if you gain access to the server all by yourself and may set it up to have your script's and the web server's GID being same so you can "fall back" to GID-based SAFE MODE and use tempnam as desired. This is true for several local work, intranet-related projects in your company etc. Just take a look at how SAFE MODE _really_ works and why it's rockingly important to use it. You should do when you're developing a company tool for public access at least.

Never forget to take a moment to think about Unix-filesystem and access rights as well ... even if you're locally running Windows to have some great IDE or similar (like me :). PHP is available on both systems, but that's not succeeding to define your work as "portable".
andi<at>splitbrain<dot>org
08-Aug-2004 10:28
tempname ignores the current umask and always creates the file with permission 0600.
anakin dot skyw at gmx dot de
04-Jul-2004 11:20
>Under UNIX (where you can rename onto an extant file and so I used link), you will have to remove both the link and the link's target.

Couldn't you do
<?php
      
if ($newFileCreated) {
          
unlink ($sysFileName);
           return
$newFileName;
       }
?>
and get the same semantics as the windows version?
bishop
01-May-2004 11:03
Creating a temporary file with a specific extension is a common requirement on dynamic websites. Largely this need arises from Microsoft browsers that identify a downloaded file's mimetype based on the file's extension.

No single PHP function creates a temporary filename with a specific extension, and, as has been shown, there are race conditions involved unless you use the PHP atomic primitives.

I use only primitives below and exploit OS dependent behaviour to securely create a file with a specific postfix, prefix, and directory.  Enjoy.

<?php
function secure_tmpname($postfix = '.tmp', $prefix = 'tmp', $dir = null) {
  
// validate arguments
  
if (! (isset($postfix) && is_string($postfix))) {
       return
false;
   }
   if (! (isset(
$prefix) && is_string($prefix))) {
       return
false;
   }
   if (! isset(
$dir)) {
      
$dir = getcwd();
   }

  
// find a temporary name
  
$tries = 1;
   do {
      
// get a known, unique temporary file name
      
$sysFileName = tempnam($dir, $prefix);
       if (
$sysFileName === false) {
           return
false;
       }

      
// tack on the extension
      
$newFileName = $sysFileName . $postfix;
       if (
$sysFileName == $newFileName) {
           return
$sysFileName;
       }

      
// move or point the created temporary file to the new filename
       // NOTE: these fail if the new file name exist
      
$newFileCreated = (isWindows() ? @rename($sysFileName, $newFileName) : @link($sysFileName, $newFileName));
       if (
$newFileCreated) {
           return
$newFileName;
       }

      
unlink ($sysFileName);
      
$tries++;
   } while (
$tries <= 5);

   return
false;
}
?>

The isWindows function is mostly left as an exercise for the reader. A starting point is below:

<?php
function isWindows() {
   return (
DIRECTORY_SEPARATOR == '\\' ? true : false);
}
?>

Like tempnam(), this function requires you to cleanup your own files later. Under UNIX (where you can rename onto an extant file and so I used link), you will have to remove both the link and the link's target. Cleanup is left entirely to the reader.
kulpp at wsg dot net
04-Feb-2004 03:57
tempnam should not be used with SAFE MODE as of 4.3.4
see http://bugs.php.net/bug.php?id=27133
phpdoc at rickbradley dot com
26-Nov-2003 07:54
The "newtempnam" recipe provided below (posted by "tempnam" on " 23-Jul-2003 08:56") has at least one race condition.  The while loop checks to make sure that the file in question doesn't exist, and then goes and creates the file.  In between the existence test and the fopen() call there is an opportunity for an attacker to create the file in question.

This is a classic race-condition, and while it seems difficult to exploit there are a number of well-known attacks against this kind of sloppy file creation.

The atomic primitives necessary to implement secure file creation are not available at the language level in PHP.  This further underscores the need for PHP-language developers to rely on the language's security primitives (including tempnam() and tempfile()) instead of rolling their own.
24-Jul-2003 01:56
The tempnam() function will not let you specify a postfix to the filename created. Here is a function that will create a new filename with pre and post fix'es. Not returns false if it can't create in the dir specified where tempnam() creates in the systems temp dir.

function newtempnam($dir, $prefix, $postfix){
   /* Creates a new non-existant file with the specified post and pre fixes */
  
   if ($dir[strlen($dir) - 1] == '/') {
       $trailing_slash = "";
   } else {
       $trailing_slash = "/";
   }
   /*The PHP function is_dir returns true on files that have no extension.
   The filetype function will tell you correctly what the file is */
   if (!is_dir(realpath($dir)) || filetype(realpath($dir)) != "dir") {
       // The specified dir is not actualy a dir
       return false;
   }
   if (!is_writable($dir)){
       // The directory will not let us create a file there
       return false;
   }
  
   do{    $seed = substr(md5(microtime().posix_getpid()), 0, 8);
       $filename = $dir . $trailing_slash . $prefix . $seed . $postfix;
   } while (file_exists($filename));
   $fp = fopen($filename, "w");
   fclose($fp);
   return $filename;
}
lreilly at lanl dot gov
29-Aug-2002 08:54
Be careful with you forward and back slashes. Innocent looking code like this...

$uploaddir = "C:/Program Files/Apache Group/Apache2/htdocs/sasdap/uploads/";
$tempFile = tempnam ($uploaddir, "TMPANAL");
$fp = fopen($tmpfname, "w");
fwrite($fp, $iqdata);
//fclose($fp);

... may show something odd when echoing $tempFile";

i.e. /Program Files/Apache Group/Apache2/htdocs/sasdap/uploads/\TMP3D.tmp
                                                      
Must... remember... to... use... backslashes...

 - Lee P. Reilly
seb at nospam dot 50carleton dot com
23-May-2001 08:24
In addition to a note previously posted, on Windows NT Server 4.0, I noticed that tempnam() only uses the first THREE characters of the specified prefix.