Reputation: 570
I want to generate some sort of ID similar to the way that Google generates URLs for their classroom service.
For example:
https://classroom.google.com/u/0/c/MTg1MKIwNTk4
I want to be able to generate the MTg1MKIwNTk4
part.
It doesn't have to be cryptographically secure or anything like that, it is just being used for a URL.
How can this be done with PHP (+MySQL)?
Thanks.
Upvotes: 0
Views: 881
Reputation: 3364
Use this code:
$charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$str = '';
$length = strlen($charset);
$count = 12;
while ($count--) {
$str .= $charset[mt_rand(0, $length-1)];
}
echo $str;
If you use PHP7, you can use random_int
instead of mt_rand
to get even better random numbers. (Proposed by @zaph in the comments).
And, of course, if you want to have random strings that are more easy to copy by hand (e.g. if you print your URLs), then you could omit some of the characters that could be ambiguous (like 'l' or '0') - (again proposed by @zaph in the comments)
Upvotes: 2
Reputation: 682
Use md5() in combination with .htaccess(Apache)/web.config(IIS) to get it.
You'll get an alphanumeric 32-char-length string. Cut it using substr()
Example:
md5('helloworld')
generate fc5e038d38a57032085441e7fe7010b0
substr(md5('helloworld'),0,10)
generates fc5e038d38
Upvotes: 0