|
|
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, "записываем в во временный файх");
fclose($handle);
unlink($tmpfname);
?>
|
|
Замечание:
Поведение функции изменилось начиная с версии PHP 4.0.3. Временный файл
также создаётся чтобы избежать состояния гонки, когда файл может появится
в файловой системе между моментом генерации строки и моментом, когда
скрипт начнёт его создавать. Обратите внимание, что вы должны удалить
файл вручную, если он больше вам не нужен; этот процесс не автоматизирован.
См. также описание функий tmpfile() и unlink().
flat at serverart dot com
04-Oct-2007 03:17
It seems that in between 5.2.2 and 5.2.4 tempnam() changed how it handles a relative path:
In 5.2.2:
$file=tempnam('tmpdownload', 'Ergebnis_'.date(Y.m.d).'_').'.pdf';
echo $file;
tmpdownload/Ergebnis_20071004_xTfKzz.pdf
In 5.2.4:
$file=tempnam('tmpdownload', 'Ergebnis_'.date(Y.m.d).'_').'.pdf';
echo $file;
/var/www/html/tmpdownload/Ergebnis_20071004_Xbn6PY.pdf
This broke quite a lot of our webpages as we try to display those pdfs (and other files) via the webbrowser and the resulting URI is of course invalid and gets the user a 404 page.
dmhouse at gmail dot com
03-Sep-2007 03:51
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'); $file = tempnam(getcwd() . 'files/tmp', 'tmp') ?>
Jason Pell
12-Jan-2007 04: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.
tux ARROBA cenobioracing PUNTO com
27-Aug-2006 05: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); is_writable($working_dir); $tempfile = tempnam($working_dir,'img');
?>
Guillaume Paramelle
06-Jun-2006 06: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 12: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
18-Sep-2005 01: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);
copy($tmpfname,'user.txt');
?>
chris
13-Jun-2005 09: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
05-Mar-2005 10:10
Note that tempnam returns the full path to the temporary file, not just the filename.
17-Feb-2005 06: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
21-Jan-2005 01: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
20-Jan-2005 11: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
02-Dec-2004 08: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
|
|