PHP Snippets

Generate a Random String

Andrei Surdu Andrei Surdu ·

This function generates a random string of a specified length. It uses str_shuffle to randomize a string of all alphanumeric characters, then uses substr to get a part of it that’s the desired length. This function is useful for generating random identifiers or tokens.

PHP Function:

function generateRandomString($length = 10) { return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length); }

// Example
echo generateRandomString(5); // 'a3G7s'
echo generateRandomString(10); // '4kU91mBvHq'

Comments

Share your thoughts and join the conversation

Loading comments...

Leave a Comment

Your email will not be published

Comments are moderated and will appear after approval

0/2000