Generating a 4-digit PIN code with PHP.

This is a short guide on how to generate a random 4-digit PIN code with PHP. In this tutorial, I’ve created a custom function that allows you to generate a PIN code of your chosen length (by default, it is four characters in length).

Let’s just dive into the code:

<?php
//Our custom function.
function generatePIN($digits = 4){
    $i = 0; //counter
    $pin = ""; //our default pin is blank.
    while($i < $digits){
        //generate a random number between 0 and 9.
        $pin .= mt_rand(0, 9);
        $i++;
    }
    return $pin;
}

//If I want a 4-digit PIN code.
$pin = generatePIN();
echo $pin, '<br>';

//If I want a 6-digit PIN code.
$pin = generatePIN(6);
echo $pin;

Basically, we use the PHP function mt_rand to generate a random number that is between 0 and 9. We then append the result of each iteration on to our PIN string. Note how I specifically used the word string there. Be warned that if you parse this number as an integer, you will lose any leading zeros. i.e. Parsing the PIN as an integer or storing it in an INT database column may lead to a loss of data! By storing it as an integer instead of a string, you are actually lessening the number of possible PIN codes, as numbers such as 0192 will become 192. If you do NOT want to have a leading zero, then you can simply do the following:

<?php

$pin = mt_rand(1000, 9999);

As you can see, we simply generate a random number that is between 1000 and 9999.

Note that the mt_rand function is not cryptographically secure. If you want a PIN that is secure, you should check out the “Cryptographically secure” section on my post: Generate A Random Number With PHP.