random-string

Random String in PHP

In some time you need to create a random String or random number. It might be for a verification code, create tokens,  a complex password, or something you are developing. You might think that its a boring and manual process. Luckily, this is not true.

Below we present a simple way to create random Strings or random number using PHP. All you need is one function with a few lines of code. Let’s begin…

Basically we define some function to create a perfect random string or random number.

First Method : 

In this method we use str_shuffle() function. With the help of this we shuffle a string and Each time str_shuffle function executes and it will randomly re-shuffle the string.  substr() function divide the string in small format that we want.

<?php
  function rand_str($lenth) {
    $str = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
    $shuffled = substr(str_shuffle($str), 0, $length);
    return $shuffled;
  }
?>

Second Method : 

In this method we use rand() function.

<?php
  function rand_string( $length ) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $<strong class="StrictlyAutoTagBold">size</strong> = strlen( $chars );
    for( $i = 0; $i < $length; $i++ ) {
        $str .= $chars[ rand( 0, $<strong class="StrictlyAutoTagBold">size</strong> - 1 ) ];
    }
    return $str;
  }
?>

Both function are very useful and popular. These function create random string or random number in each time.

Related Posts


2 thoughts on “Random String in PHP

  1. Pillen Shop

    You realize thus considerably relating to this topic, made me individually believe it from numerous various angles. Its like women and men aren’t fascinated unless it’s one thing to accomplish with Woman gaga! Your personal stuffs excellent. At all times take care of it up!

    Reply
  2. hosting gratis sin publicidad host gratis servidor gratis

    Woah this kind of weblog is actually amazing i enjoy examining your posts. Continue to be the great! You already know, a great deal of people feel the need about because of this facts, you can help them to greatly.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


*