Генерация уникального имени для файла

Create a file with a unique name with PHP

The PHP function tempnam() creates a file with a unique name. This can be useful if you need to output some data into a temporary file for one reason or another, and the actual name of the file is not important. The most simple usage of tempnam() is as follows:

This will create a zero length filename in the system’s temporary directory and return the name generated to $filename. An example of the value returned is as follows:

Creating a temporary file in a specific location

You can specify the location the file should be created by setting the first parameter. If it’s left blank (as in the first example above), does not exist, or is a directory the process does not have write access to, then the system temporary directory will be used instead.

$filename = tempnam('/tmp/test', ''); echo $filename; // outputs e.g. /tmp/test/fA6u4e

The above example specifies /tmp/test as the output directory. This directory must be writable by the process to create a file there. For example, if running under the Apache web server, then the user Apache runs as must have write access to the /tmp/test directory.

Adding a prefix to the temporary filename

Finally, the second parameter allows you to specify a prefix that will be the first part of the filename, as show in the example below:

$filename = tempnam('/tmp/test', 'myprefix-'); echo $filename; // outputs e.g. /tmp/test/myprefix-fA6u4e

Using the temporary file

Calling the tempnam() function creates the file as a zero length file, and the PHP script does not actually delete it when the process completes running. To use the file, use the regular fopen() etc functions and then delete the file when you have finished, eg:

$filename = tempnam('', ''); $fp = fopen($filename, 'w'); . fclose($fp); . unlink($filename);

Summary

In summary, the tempnam() function allows you to create a temporary file in PHP with a unique name which you can then use with the regular file functions, and which you then need to remove yourself at the end of your script if you need it deleted afterwards.

Читайте также:  Язык программирования html цвета

Источник

Генерация уникального имени файла на PHP

Ниже представлены примеры генерации уникального имени файла, чтобы исключить возможной перезаписи какого-либо файла новым файлом. В зависимости от сложности проекта можно выбрать подходящий вариант и использовать его на практике.

Самый простой вариант – использовать встроенную в PHP функцию uniqid() :

// Строка длиной в 13 символов $fileName = uniqid(); // Используем префикс // Например: php_5dcb4d75361c9 $fileName = uniqid('php_'); // Строка длиной в 23 символа // Например: php_5dcb4eb2368202.10751068 $fileName = uniqid('php_', true);

Более сложный (более близок к уникальности) вариант — использовать uniqid() в сочетании с функцией md5() :

// Строка длиной в 32 символа // Например: b100eaee3c552beb1a83aa4927f012c9 $fileName = md5(uniqid());

Вместо uniqid() можно использовать другую функцию, например, microtime() . Эта функция возвращает текущую метку времени Unix с микросекундами:

$fileName = md5(microtime()); // С точностью до микросекунд $fileName = md5(microtime(true));

Усложним пример (придадим больше уникальности):

$fileName = md5(microtime() . rand(0, 1000));

Если необходимо имя короче, чем 32 символа, то можно просто обрезать строку до нужной длины:

// Строка длиной в 15 символов $fileName = substr(md5(microtime() . rand(0, 1000)), 0, 15);

Если проект небольшой или даже средний, то вышеуказанные примеры вполне себе годятся для генерации уникальных имён файлов. Но, если проект сложный и очень много файлов загружается, то есть вероятность перезаписи какого-либо файла новым файлом при случайной генерации такого же имени для нового файла. Появляется проблема неконтролируемости уникальности файлов. Иными словами, встаёт необходимость проверки на отсутствие такого же файла. Приведу простой пример. Для удобства я соберу весь код в одном файле:

       
while (file_exists($file)); return $file; > // Загружаем файл if ($_FILES) < $path = 'uploads/'; $extension = strtolower(substr(strrchr($_FILES['image']['name'], '.'), 1)); $file = $path . randomFileName($extension); move_uploaded_file($_FILES['image']['tmp_name'], $file); >

Здесь осуществляется проверка на существование файла. Если файл с таким именем уже существует, то генерируется следующее имя.

Есть ещё вариант — использовать функцию sha1_file() . Она возвращает хеш — 40-символьное шестнадцатеричное число:

Или с проверкой на отсутствие файла с таким же именем:

 while (file_exists($file)); return $file; > // Загружаем файл if ($_FILES) < $path = 'uploads/'; $tmp_name = $_FILES['image']['tmp_name']; $extension = strtolower(substr(strrchr($_FILES['image']['name'], '.'), 1)); $file = $path . randomFileName($extension); move_uploaded_file($tmp_name, $file); >

Есть ещё вариант — генерировать уникальное имя для файла, при этом в имени будут и директории:

 while (file_exists($file)); return $file; > // Загружаем файл if ($_FILES) < $path = 'uploads/'; $tmp_name = $_FILES['image']['tmp_name']; $extension = strtolower(substr(strrchr($_FILES['image']['name'], '.'), 1)); $file = randomFileName($extension); $dir = substr($file, 0, 16); if (!is_dir($dir)) mkdir($path . $dir, 0777, true); move_uploaded_file($tmp_name, $path . $file); >

Название файла будет примерно таким: uploads/7ce/824/286eeca87.jpg Причём uploads/7ce/824/ это вложенные директории. В примере указано, что если этих директорий нет, то их необходимо создать.

Источник

Unique and temporary file names in php

I am not sure about the process that you are following for uploading files, but another way to handle file uploads is with PHP’s built in handlers. So basically, What I would do is split the original filename from the the extension And then generate a unique file name as below and then append the extension Hoping you find this useful Solution 1: AFAIK it’s a great way to name the files, although I would check and maybe tack on a random number.

Читайте также:  Заголовок страницы

Best way to give a file an unique name with php

Is the file temporary? Then maybe tempnam. Or maybe look at uniqid.

time is not sufficiently unique, all it takes to get clashes is that line being ran twice in the same second.

This is what tempnam and tmpfile are meant for.

Despite the name, you can use tempnam to create files outside of the systems temporary directory, so they will be permanent.

Files created using tmpfile are temporary and are removed at the end of the program at the latest.

The following is what I typically use for a random string and then you can append the file type if needed to the end of it

How to unlink the temporary files from /tmp folder in, The correct thing to do is not delete the files in /tmp. The system will clear files in /tmp by default every time the system is rebooted. This is the default but can be re-configured to delete more frequently. Or place the temporary files in a another directory.

Unique and temporary file names in PHP

Unique and temporary file names in PHPPHP [ Ext for Developers : https://www.hows.tech/p/recommended.html ] Unique and temporary

How to Efficiently by Time generate random unique temp File Name for storing in Custom Directory?

So basically, What I would do is split the original filename from the the extension

And then generate a unique file name as below and then append the extension

 $fileNameNew = date('Ymdhis',time()).mt_rand().".".$fileActualExt; //current date with hour, minutes and exact seconds + time + random digits ?> 

Hoping you find this useful

Storing temporary file’s name and path in PHP, I am trying to create a web-based interface that would allow a user to run a specific bash script in background, gets its content and delete the temporary file that has been used to store the outpu

AFAIK it’s a great way to name the files, although I would check file_exists() and maybe tack on a random number.

You need to store that filename in a variable and reference it again later, instead of relying on the algorithm each time. This could be stored in the user $_SESSION , a cookie, a GET variable, etc between pageloads.

Читайте также:  Html input name массив

Just want add that php has a function to create identifiers: uniqid . You can also prefix the identifier with a string (date maybe?).

Always validate your user’s input, and the server headers!

I would recommend storing the file name in the session (as per AI). If you store it in one of the other variables, it is more likely for the end user to be able to attack the system through it. MD5 of user concatenated with rand() would be a nice way to get a long list of unique values. Just using rand() would probably have a higher percentage of conflicts.

I am not sure about the process that you are following for uploading files, but another way to handle file uploads is with PHP’s built in handlers. You can upload the file and then use the «secure» methods for pulling uploaded files out of the temporary space. (the temporary space in this instance can be safely located outside of the open base dir directive to prevent tampering). is_uploaded_file() and move_uploaded_file() from: http://php.net/manual/en/features.file-upload.post-method.php example 2 might handle the problem you are encountering.

Definitely check for an existing file in that location if you are choosing a filename on the fly. If user input is allowed in any way shape or form, validate and filter the argument to make sure it is safe. Also, if the storage folder is web accessible, make sure you munge the name and probably the extension as well. You do not want someone to be able to upload code and then be able to execute it. That officially leads to BAD activities.

Unique and temporary file names in PHP?, I’ve used uniqid () in the past to generate a unique filename, but not actually create the file. $filename = uniqid (rand (), true) . ‘.pdf’; The first parameter can be anything you want, but I used rand () here to make it even a bit more random. Using a set prefix, you could further avoid collisions with other temp files in the system. Code samplewhile (true) Feedback

Saving temporary file name after uploading file with uplodify

Sorry i tried one more time with $_POST[‘PHPSESSID’] and is working right now , thanks for help

Best method to generate unique filenames when, I usually either create a UID using uniqid () function for the filename or create a folder with the name of the username who is uploading the file and leave the original filename. The disadvantage of the first one is that you will have to save the original filename somewhere to show to the user. Share Improve this answer

Источник

Оцените статью