0

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.

Zach P
  • 560
  • 10
  • 30

2 Answers2

2

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)

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27
  • It is better to use the [Base58](https://en.wikipedia.org/wiki/Base58) character set, it does not have ambitious characters, the letters omitted are: 0 (zero), O (capital o), I (capital i) and l (lower case L) as well as the non-alphanumeric characters + (plus) and / (slash). – zaph Jun 06 '16 at 13:35
  • It is better to use `random_int` than `mt_rand`. – zaph Jun 06 '16 at 13:41
  • If you use PHP7, then this should be the option. I'll add it to my answer, thanks @zaph – JSchirrmacher Jun 06 '16 at 14:02
0

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

Nacho M.
  • 672
  • 4
  • 9
  • 2
    This solution is nice and short, but is not yet the solution requested by the OP, because the string can only contain a small subset of characters. – JSchirrmacher Jun 06 '16 at 13:19
  • You're right @JoachimSchirrmacher Anyway , this would work when it is not mandatory the string mixes upper and lower chars. Thank you for the correction anyway. – Nacho M. Jun 06 '16 at 13:22
  • Where does it say OP only wants a small subset of chars? It only stipulates alpha numeric chars. I don't see why this answer is downvoted. – Ally Jun 06 '16 at 15:02
  • I don't know either. And, actually, the OP didn't say he wanted a subset, but the answer is restricted to do so, since `md5()` uses only hex digits. – JSchirrmacher Jun 06 '16 at 15:08