Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create random unique alphanumeric string in PHP [duplicate]

Tags:

php

php-5.4

I have the following code that lets a user register his/her email on a website with a password, and returns them a unique pin.

<?
if($_POST['srSubmit'] && $_POST['srEmail'] && $_POST['srPass']) {
    $conn = mysql_connect('localhost','','');
    mysql_select_db("db_test",$conn);
    while(1) {
        $pin = rand(111111,999999);
        $sel = mysql_query("SELECT * FROM formusers WHERE pin = '$pin'");
        if(mysql_num_rows($sel) != 0) { continue; }

        mysql_query("INSERT INTO formusers(email,password,pin) VALUES('".$_POST['srEmail']."','".$_POST['srPass']."','".$pin."')");
        if(mysql_affected_rows()!=-1)  {
            echo "Pin:" . $pin;
            exit;
        } else {
            echo "Existing email, try again<br />";
        }
        break;
    }

}
?>
<form method="POST" action="">
<input type="email" name="srEmail" value="" placeholder="Email" /><br />
<input type="password" name="srPass" value="" placeholder="Password" /><br />
<input type="submit" name="srSubmit" value="Register" />
</form>

I want to associate a unique URL with each user (server.com/[unique-9-digit-alphanumeric-code], such that I can create a relatively secure admin page that users can access without necessarily needing to know their password.

Is there an easy way to do this with a PHP function (it doesn't have to be 9 digits, just long and random), or do I need to generate my own random alpha-numeric string and then post that to the database? How would you suggest coding this?

like image 413
alias51 Avatar asked Aug 19 '26 12:08

alias51


2 Answers

A lot of times, when I need a unique string I use this mysql query: select HIGH_PRIORITY UNIX_TIMESTAMP(); to get a unique 10 digit number like 1374517262 and then append or prepend characters.

like image 59
The Debi Avatar answered Aug 22 '26 01:08

The Debi


http://snipplr.com/view/5444/

This is a nice function that will generate random pronounceable passwords. This may help you get close to what you are trying to accomplish.

like image 37
Michael Valentino Avatar answered Aug 22 '26 01:08

Michael Valentino