I do:
$code = str_random(10); //would produce a secret code of 10 chars.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a booking system and want to generate a cancellation code, say 6 characters or so, that can be used to cancel a booking:
For example: /bookings/cancel/Hk7D#A
The code should be as short as possible, still be reasonably secure.
On the same note, I would also like to be able to generate API tokens. These are obviously a lot longer, but perhaps there is a function/package that can be used for both?
Ideally, one should be able to something like this: $code = new SecretCode(6); // would produce a secret code of 6 chars.
Any suggestions?
This is a class that I created which I have found useful:
class UUID {
/**
* @var
*/
public $prefix;
/**
* @var
*/
public $entropy;
/**
* @param string $prefix
* @param bool $entropy
*/
public function __construct($prefix = '', $entropy = false)
{
$this->uuid = uniqid($prefix, $entropy);
}
/**
* Limit the UUID by a number of characters
*
* @param $length
* @param int $start
* @return $this
*/
public function limit($length, $start = 0)
{
$this->uuid = substr($this->uuid, $start, $length);
return $this;
}
/**
* @return string
*/
public function __toString()
{
return $this->uuid;
}
}
It's actually pretty damn flexible too. For example:
$code = new UUID;
return $code; // Will return something like 53ef6b2ae4da1
$code = new UUID('secret_');
return $code; // Will return something like secret_53ef6b2ae4da1
$code = new UUID;
return $code->limit(6); // Will return something like 53ef6b
Please note that this should not be used for anything that needs to be cryptographically secure. PHP's "uniqid" function is basically just random characters generated from the "microtime" function.
Please or to participate in this conversation.