©
This document uses PHP Chinese website manual Release
(PHP 4, PHP 5, PHP 7)
tempnam — 建立一个具有唯一文件名的文件
$dir
, string $prefix
)在指定目录中建立一个具有唯一文件名的文件。如果该目录不存在, tempnam() 会在系统临时目录中生成一个文件,并返回其文件名。
dir
The directory where the temporary filename will be created.
prefix
产生临时文件的前缀。
Note: Windows uses only the first three characters of prefix.
返回新的临时文件名,出错返回 FALSE
。
版本 | 说明 |
---|---|
4.0.6 |
在 PHP 4.0.6 之前, tempnam()
函数的行为取决于系统。在 Windows 下 TMP
环境变量会越过 dir
参数,在 Linux 下 TMPDIR
环境变量优先,而在 SVR4 下总是使用 dir
参数,如果其指向的目录存在的话。如果有疑问请参考系统文档中的
tempnam(3) 函数。
|
4.0.3 | 本函数的行为在 4.0.3 版中改变了。也会建立一个临时文件以避免竞争情形,即有可能会在产生出作为文件名的字符串与脚本真正建立该文件之间会在文件系统中存在同名文件。注意,如果不再需要该文件则要删除此文件,不会自动删除的。 |
Example #1 tempnam() 例子
<?php
$tmpfname = tempnam ( "/tmp" , "FOO" );
$handle = fopen ( $tmpfname , "w" );
fwrite ( $handle , "writing to tempfile" );
fclose ( $handle );
// do here something
unlink ( $tmpfname );
?>
Note: 如果 PHP 不能在指定的
dir
参数中创建文件,则退回到系统默认值。 在 NTFS 文件系统中,同样的情况也发生在dir
中文件数超过 65534 个的时候。
[#1] wapmorgan [2014-05-26 17:54:21]
Notice that tempnam will return NULL (not false) if the second parameter <prefix> isn't transferred:
<?php
var_dump(tempnam(sys_get_temp_dir())); // NULL
?>
also the warning will be generated:
Warning: tempnam() expects exactly 2 parameters, 1 given in php shell code ...
[#2] divinity76+yaoiporn at gmail dot com [2013-09-29 14:00:22]
if you don't want to take care of deleting the file yourself, and you don't need a custom prefix, you can use
$file_location=stream_get_meta_data(tmpfile())['uri'];
file will be created automatically, and deleted automatically on script close (thanks to tmpfile()) i found this useful for CURLOPT_COOKIEFILE (which wants a file location, not a handle)
[#3] Steve Clay [2013-09-24 14:59:46]
You don't need tempdir(). Just use tempnam() and replace it with a directory of the same name:
<?php
$temp_dir = tempnam('/tmp', 'prefix');
unlink($temp_dir);
mkdir($temp_dir);
[#4] Anonymous [2012-02-13 19:44:30]
tempnam will not create file in unauthorized area.
Meaning you need access permissions to the temp dir ($dir) in order to create a file there.
[#5] tomas at slax dot org [2010-06-03 02:31:55]
Beware: functions are not atomic. If many processes call the same function at the same time, you may end up with unwanted behavior.
If you need your own variant of tempnam, use something like this:
<?php
function tempnam_sfx($path, $suffix)
{
do
{
$file = $path."/".mt_rand().$suffix;
$fp = @fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
// call it like this:
$file = tempnam_sfx("/tmp", ".jpg");
?>
You may replace mt_rand() by some other random name generator, if needed.
[#6] anthon at piwik dot org [2010-04-06 16:20:20]
The file created by tempnam() will have file permissions that reflect the current umask applied to the default (e.g., 0600 or -rw-------). This is the case whether the umask is set before starting the web server process, or set by an earlier call to PHP's umask() function.
For example, if the current umask is 0022, the temporary file is created with permissions 0600 (read/write by owner).
Also, if the current umask is 0222, the temporary file is created with permissions 0400 (read-only by owner). (This is problematic if your code then tries to open the temporary file for writing.)
It's important to remember that the umask revokes permissions. In neither of the above examples are the group, other, or execute permissions set.
See: umask(), chmod().
[#7] Artur Graniszewski [2010-03-31 10:57:22]
tempnam() function does not support custom stream wrappers registered by stream_register_wrapper().
For example if you'll try to use tempnam() on Windows platform, PHP will try to generate unique filename in %TMP% folder (usually: C:\WINDOWS\Temp) without any warning or notice.
<?php
// << ...custom stream wrapper goes somewhere here...>>
echo '<pre>';
error_reporting(E_ALL);
ini_set('display_errors', true);
clearstatcache();
stream_register_wrapper('test', 'MemoryStream');
mkdir('test://aaa');
mkdir('test://aaa/cc');
mkdir('test://aaa/dd');
echo 'PHP '.PHP_VERSION;
echo '<br />node exists: '.file_exists('test://aaa/cc');
echo '<br />node is writable: '.is_writable('test://aaa/cc');
echo '<br />node is dir: '.is_dir('test://aaa/cc');
echo '<br />tempnam in dir: '.tempnam('test://aaa/cc', 'tmp');
echo "<br /></pre>";
?>
ouputs:
--------------------
PHP 5.2.13
node exists: 1
node is writable: 1
node is dir: 1
tempnam in dir: C:\Windows\Temp\tmp1D03.tmp
If you want to create temporary file, you have to create your own function (which will probably use opendir() and fopen($filename, "x") functions)
[#8] koyama [2009-08-30 17:39:53]
Watch out using a blank $dir as a "trick" to create temporary files in the system temporary directory.
<?php
$tmpfname = tempnam('', 'FOO'); // not good
?>
If an open_basedir restriction is in effect, the trick will not work. You will get a warning message like
Warning: tempnam() [function.tempnam]: open_basedir restriction in effect.
File() is not within the allowed path(s): (/var/www/vhosts/example.com/httpdocs:/tmp)
What works is this:
<?php
$tmpfname = tempnam(sys_get_temp_dir(), 'FOO'); // good
?>
[#9] hm2k at php dot net [2009-01-28 09:15:11]
<?php
function tempdir($dir=false,$prefix='php') {
$tempfile=tempnam('','');
if (file_exists($tempfile)) { unlink($tempfile); }
mkdir($tempfile);
if (is_dir($tempfile)) { return $tempfile; }
}
echo tempdir();
// returns: /tmp/8e9MLi
?>
[#10] dmhouse at gmail dot com [2007-09-03 03:51:56]
Guillaume Paramelle's comments below are worth underlining: tempnam() will not accept a relative path for its first directory. If you pass it one, it will (on Windows XP at least) create the temporary file in the system temp directory.
The easiest way to convert a relative path to an absolute path is to prepend getcwd():
<?php
$file = tempnam('files/temp', 'tmp'); // Wrong!
$file = tempnam(getcwd() . 'files/tmp', 'tmp') // Right.
?>
[#11] Jason Pell [2007-01-12 04:47:47]
I want to guarantee that the file will be created in the specified directory or else the function should return FALSE, I have a simple function that works, but I am unsure if its a potential security issue.
function dir_tempnam($dir, $prefix)
{
$real_dir_path = realpath($dir);
if (substr($real_dir_path, -1) != '/')
$real_dir_path .= '/';
$tempfile = tempnam($real_dir_path, $prefix);
$name = basename($tempfile);
if(is_file($real_dir_path.$name))
return $name;
else
{
@unlink($name);
return FALSE;
}
}
This function returns just the name of the temporary file in the specified directory, or FALSE.
Obviously it could return the entire $tempfile, but in my case, I actually want the basename value seperate.
[#12] tux ARROBA cenobioracing PUNTO com [2006-08-27 17:19:54]
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...
?>
[#13] Ron Korving [2006-02-03 00:32:51]
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;
}
?>
[#14] KOmaSHOOTER at gmx dot de [2005-09-18 13:51:48]
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');
?>
[#15] php at REMOVEMEkennel17 dot co dot uk [2005-03-05 22:10:41]
Note that tempnam returns the full path to the temporary file, not just the filename.
[#16] [2005-02-17 06:13:20]
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."
[#17] Sebastian Kun [2005-01-21 13:03:04]
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).
[#18] Nick Smith [2005-01-20 11:35:20]
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.
[#19] anakin dot skyw at gmx dot de [2004-07-04 08:20:55]
>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?
[#20] bishop [2004-04-30 20:03:58]
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.
[#21] phpdoc at rickbradley dot com [2003-11-25 15:54:28]
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.
[#22] lreilly at lanl dot gov [2002-08-28 17:54:51]
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