-2

How can I generate a random string, 20 characters long, A-Z (no lower case), 0-9 only?

I searched online but most scripts to do this are huge (50+ lines). Is there something simpler (maybe 1 line)?

2
  • Scrapping the answer I wrote as it was identical to the one linked here. Oh search boxes are heaven sent Commented Jan 13, 2014 at 18:51
  • possible duplicate of Generating (pseudo)random alpha-numeric strings Commented Jan 13, 2014 at 23:20

2 Answers 2

3

Will this suffice ?

<?php
echo strtoupper(substr(sha1(uniqid()),0,20));

OUTPUT :

A71463EA326B72981D21
Sign up to request clarification or add additional context in comments.

2 Comments

Pretty wiz :-) Nice one
Only generates 0-9A-F, leaving out 20 of the 36 possible chars.
3

You could create a string with all the character you want that could be in the random string

$chars = 'ABCDEFG...0123456789';

and then create a for loop that picks a random letter or number in the chars string for 20 timer

$randstring = '';
$string_length;
for ($a = 0; $a < $string_length; $a++) {
  $randstring .= $chars[rand(0, strlen($chars) - 1)];
}

Hope it helped!

1 Comment

Ticks all of the boxes, if I were the asker this is the answer I would accept.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.