Unique Identification for file/ folder name, ID, table key, invoice/ order number
We need create unique number/name/values for various reasons. We need to create files with unique names, unique folders names, and primary key in table, index key in table and invoice number, order no and so on.
Create file with unique file name
PHP function tempnam() (not tempname ())
Syntax: string tempnam (string dir, string prefix)
This function creates a file with unique filename with access permission set to 0600, in the specified directory.
If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that. In my case file is created here: C:\WINDOWS\TEMP\uniquefile5.tmp
<?php $uFile = tempnam("C:\Inetpub\PHPScript", "uni"); echo $uFile; // where is my new file with unique name $handle = fopen($uFile, "w"); fwrite($handle, "write to this file with unique file name"); fclose($handle); ?>
My file created was C:\Inetpub\PHPScript\uniA.tmp. Every time file name will be different.
You can use prefix for giving some meaning to new filename created. It can be empty also. Then file created will be like it: C:\Inetpub\PHPScript\B.tmp
It is also possible giving empty directory name. Then for me it is creating filename in C:\.
PHP function uniqid()
This function uniqid will Generate a unique ID for you.
string uniqid ( string prefix [, bool lcg])
It will create prefixed unique identifier based on current time in microseconds.
echo uniqid() ;
This function will return (13 + prefix length) characters long identifier. If “lcg” is true then it will return (prefix length + 23) characters.
Make guessing very difficult:
$uniqueID = md5 (uniqid (rand(), true));
Now you have unique id, you can use it in a way you like.
Create a temporary file with unique name
PHP function tmpfile
This function tmpfile will create a temporary file in write mode similar to fopen. This file will be closed by fclose() or when the script ends.
<?php $temp = tmpfile(); fwrite($temp, "writing to tempfile"); fseek($temp, 0); echo fread($temp, 1024); fclose($temp); // this removes the file ?>