Random Code in PHP

If you are looking for on how to create Random Code in PHP then you are at the right place. In this tutorial, we are going to learn on how to create random code using PHP. You can use it this simple project in your existing web application or systems like in registration form, before sending information you can use the random code to confirm it before sending data to the database or you can use it as a random code for your selling items in POS web project, etc. Take a look the source code below. This simple code, we are going to use it to have a random code. This source code where we can get a random code.
  1. <?php
  2. $code_variable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
  3. ?>
Full Source Code
  1. <?php
  2.  
  3. function randomCode()
  4. {
  5. $code_variable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
  6. srand((double)microtime() * 1000000);
  7. $i = 0;
  8. $rand_Code = '';
  9. while ($i <= 7)
  10. {
  11. $num = rand() % 33;
  12. $tmp = substr($code_variable, $num, 1);
  13. $rand_Code = $rand_Code . $tmp;
  14. $i++;
  15. }
  16.  
  17. return $rand_Code;
  18. }
  19.  
  20. ?>
And, we have to create a button for the refreshing of the page, so we can get easily a new code on the web page.
  1. <a href="index.php">
  2. <button type="button">
  3. Get New Code
  4. </button>
  5. </a>
Lastly, this source code where we can display the random code that we get in the PHP query above.
  1. <div style="width:30%;">
  2. <b>
  3. <?php echo randomCode(); ?>
  4. </b>
  5. </div>

Output

Result

Add new comment