How to generate random string in PHP

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to generate random string in PHP

Have you ever needed to generate a random password from a given set of chars in PHP? You could also probably wanted a password salt used for encrypting the user password. Well here are two solutions which I can think of at the moment to help you generate the random string in php.

1st solution (php native)

The first solution is by using the str_shuffle() function, the same as shuffle() which I’ve showed you how to suffle an array when choosing a random background image, you would use this function on a specific string to shuffle its characters..

(PHP 4 >= 4.3.0, PHP 5)

str_shuffle — Randomly shuffles a string

You can of course use the function directly without creating your own function for this, but for the sake of this being more easily used in different cases, this how you do it.

Output

The output would look similar to:

Of course you can control the length you need if you change $length to a different value.

2nd solution (implemented)

The second solution is by generating the random string manually. The same with a length set specific to 10.

Output

There are probably other ways to do this, but for now, these two solutions should suffice. But if you’re looking in generating random strings for passwords, you should probably also check our article on hash encryption method in php.

  • Michael

    There’s a difference between your two solutions. Solution #1 does not repeat any characters more than once and Solution #2 does.

    Also, here’s an approach I pulled out of my own code that has the same output as Solution #2:

Request an article ←