Skip to main content

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
  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. }
  17. return $rand_Code;
  18. }
  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>



Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.


1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.