As a direct answer to your question
To generate a pseudo random string, you can use this function :
function getPseudoRandomString($length = 4) {
$base64Chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/';
$result = '';
for ($i = 0; $i < $length; ++$i) {
$result .= $base64Chars[mt_rand(0, strlen($base64Chars) - 1)];
}
return $result;
}
NOTE : This generates a pseudo random string, there is no way to be sure the string is unique.
To get a "more unique" string
first, you should use a longer string : 4 chars is really small : there are only 16 million possibilities with a set of 64 chars.
Then, If you want to add more unicity, you can concatenate a random generated string with the result of uniqid('', true)
http://php.net/manual/en/function.uniqid.php
To be sure the string has never been generated
The only way to to be sure the string has never been generated is to save all generated strings in a database and when you generate a new string, you have to check if the string already exists in the database to generate a new one if needed.
The generator function will look like
function generateUniqueString()
do {
$string = generateString();
while (is_in_database($string));
save_in_database($string);
return $string;
}