Unique and Temporary File Names in PHP

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.

$filename = uniqid('MyApp', true) . '.pdf';

From there, you just create the file. If all else fails, put it in a while loop and keep generating it until you get one that works.

while (true) {
$filename = uniqid('MyApp', true) . '.pdf';
if (!file_exists(sys_get_temp_dir() . $filename)) break;
}

How to create a temp file with a specific name

If you want to create a unique filename you can use tempnam().

This is an example:

<?php
$tmpfile = tempnam(sys_get_temp_dir(), "FOO");

$handle = fopen($tmpfile, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

unlink($tmpfile);

UPDATE 1

temporary file class manager

<?php
class TempFile
{
public $path;

public function __construct()
{
$this->path = tempnam(sys_get_temp_dir(), 'Phrappe');
}

public function __destruct()
{
unlink($this->path);
}
}

function i_need_a_temp_file()
{
$temp_file = new TempFile;
// do something with $temp_file->path
// ...
// the file will be deleted when this function exits
}

Best method to generate unique filenames when uploading files PHP

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.

php Unique filename when uploading

You can use the uniqid() function to generate a unique ID

/**
* Generate a unique ID
* @link http://www.php.net/manual/en/function.uniqid.php
* @param prefix string[optional] <p>
* Can be useful, for instance, if you generate identifiers
* simultaneously on several hosts that might happen to generate the
* identifier at the same microsecond.
* </p>
* <p>
* With an empty prefix, the returned string will
* be 13 characters long. If more_entropy is
* true, it will be 23 characters.
* </p>
* @param more_entropy bool[optional] <p>
* If set to true, uniqid will add additional
* entropy (using the combined linear congruential generator) at the end
* of the return value, which should make the results more unique.
* </p>
* @return string the unique identifier, as a string.
*/
function uniqid ($prefix = null, $more_entropy = null) {}

generate random string in php for file name

function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));

for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}

return $key;
}

echo random_string(50);

Example output:

zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8

EDIT

Make this unique in a directory, changes to function here:

function random_filename($length, $directory = '', $extension = '')
{
// default to this files directory if empty...
$dir = !empty($directory) && is_dir($directory) ? $directory : dirname(__FILE__);

do {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));

for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
} while (file_exists($dir . '/' . $key . (!empty($extension) ? '.' . $extension : '')));

return $key . (!empty($extension) ? '.' . $extension : '');
}

// Checks in the directory of where this file is located.
echo random_filename(50);

// Checks in a user-supplied directory...
echo random_filename(50, '/ServerRoot/mysite/myfiles');

// Checks in current directory of php file, with zip extension...
echo random_filename(50, '', 'zip');

Generating unique filenames with tempnam

As cantsay suggested, I made a php script to look for identical values.

function tempnam_tst() {
for ($i=0; $i < 250000 ; $i++) {

$tmp_name = tempnam('/tmp/', '');
unlink($tmp_name);
$arr[$i] = $tmp_name;
}

return array_intersect($arr, array_unique(array_diff_key($arr, array_unique($arr))));
}

$arr = array();

do {
$arr = tempnam_tst();
} while ( empty($arr) );

echo 'Matching items (case-sensitive):<br>';
echo '<pre>';
print_r($arr);
echo '</pre>';

Result:


Matching items (case-sensitive):

Array
(
[59996] => /tmp/8wB6RI
[92722] => /tmp/KnFtJa
[130990] => /tmp/KnFtJa
[173696] => /tmp/8wB6RI
)

From what I can see, tempnam() does not always generate an unique name.

PHP: Is the $_FILES ['tmp_name'] unique?

It's unique in that you can never have two files with the same name at any given time. However since the files are temporary they will most likely be deleted shortly after their creation, so the filenames free up again.

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

<?php 

$fileExt = explode('.', $filename);

$fileActualExt = strtolower(end($fileExt));

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



Related Topics



Leave a reply



Submit