# Generating OTP (One time Password) in PHP

Now these days, OTP (one time password) is mandatory in almost each and every service. A developer can generate OTP in many ways but the challenge is not to be predictive as any one can predict the OTP and can exploit the service.

Some of popular format of OTPs are:

- 4 or 6 digit Numeric OTP.
- 4 or 6 alphabetic (lowercase / uppercase) OTP.
- 4 or 6 digit alphanumeric OTP.

Examples for n-digit numeric OTP:

Input : n = 4 Output : 8723 Input : n = 8 Output : 23914072

**Note:** The output of program will be different in every execution.

One of the best way to generate OTP is to use random function. But using random function directly can be dangerous. So here is an method which uses random function and some algorithm for generating the n-digit numeric OTP.

**Program:**

`<?php ` ` ` `// Function to generate OTP ` `function` `generateNumericOTP(` `$n` `) { ` ` ` ` ` `// Take a generator string which consist of ` ` ` `// all numeric digits ` ` ` `$generator` `= ` `"1357902468"` `; ` ` ` ` ` `// Iterate for n-times and pick a single character ` ` ` `// from generator and append it to $result ` ` ` ` ` `// Login for generating a random character from generator ` ` ` `// ---generate a random number ` ` ` `// ---take modulus of same with length of generator (say i) ` ` ` `// ---append the character at place (i) from generator to result ` ` ` ` ` `$result` `= ` `""` `; ` ` ` ` ` `for` `(` `$i` `= 1; ` `$i` `<= ` `$n` `; ` `$i` `++) { ` ` ` `$result` `.= ` `substr` `(` `$generator` `, (rand()%(` `strlen` `(` `$generator` `))), 1); ` ` ` `} ` ` ` ` ` `// Return result ` ` ` `return` `$result` `; ` `} ` ` ` `// Main program ` `$n` `= 6; ` `print_r(generateNumericOTP(` `$n` `)); ` ` ` `?> ` |

*chevron_right*

*filter_none*

**Output:**

561862

## Recommended Posts:

- Dynamically generating a QR code using PHP
- Generating Random String Using PHP
- Strong Password Suggester Program
- Maximum removal from array when removal time >= waiting time
- PHP | time() Function
- PHP | Date and Time
- How to convert timestamp to time ago in PHP ?
- Queries of nCr%p in O(1) time complexity
- Measuring script execution time in PHP
- Count of sub-strings that do not contain all the characters from the set {'a', 'b', 'c'} at the same time
- Polynomial Time Approximation Scheme
- Schedule elevator to reduce the total time taken
- Convert timestamp to readable date/time in PHP
- PHP | Spreadsheet | Setting a date and/or time value in a cell
- Extended Mo's Algorithm with ≈ O(1) time complexity

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.