php - Generate random and if not exist in DB,add it -
i'm there,but missing.my php app:
1)user requesting server
2)the server generating long unique string , checks if exists in db:if yes generate again(until doesn't exists),if no add db , finish. logic should executed single request,i.e user should not request/refresh page if generated string exist.
i stuck in yes part.
my code (disclaimer:i not own parts of following code)
<?php class genpass { private $db; function __construct() { $this->db=new mysqli('localhost', 'user', 'pass', 'db'); $this->db->set_charset("utf8"); $this->db->autocommit(false); } function __destruct() { $this->db->close(); } function isused($uid) { $stmt=$this->db->query("select * id udid='".$uid."'")or die($this->db->error); while($stmt->num_rows <1) { $newnum = $this->generatestrongpassword(); $newcheck=$this->db->query("select * id udid='".$newnum."'")or die($this->db->error); if ($newcheck->num_rows >= 1) { echo $newnum . " exists! \n"; <- if exists?which part of script should run again } else { $this->db->query("insert id (udid) values ('".$newnum."')")or die($this->db->error); echo "$newnum - can isnert@!@!@"; break; } } } public function generatestrongpassword($length = 3, $add_dashes = false, $available_sets = 'lu') { $sets = array(); if(strpos($available_sets, 'l') !== false) $sets[] = 'ab';//'abcdefghjkmnpqrstuvwxyz'; if(strpos($available_sets, 'u') !== false) $sets[] = 'ab';//'abcdefghjkmnpqrstuvwxyz'; if(strpos($available_sets, 'd') !== false) $sets[] = '23456789'; if(strpos($available_sets, 's') !== false) $sets[] = '!@#$%&*?'; $all = ''; $password = ''; foreach($sets $set) { $password .= $set[array_rand(str_split($set))]; $all .= $set; } $all = str_split($all); for($i = 0; $i < $length - count($sets); $i++) $password .= $all[array_rand($all)]; $password = str_shuffle($password); if(!$add_dashes) return $password; $dash_len = floor(sqrt($length)); $dash_str = ''; while(strlen($password) > $dash_len) { $dash_str .= substr($password, 0, $dash_len) . '-'; $password = substr($password, $dash_len); } $dash_str .= $password; return $this->$dash_str; } } $obj = new genpass; $ran=$obj->generatestrongpassword(); $obj->isused($ran); ?>
you're using function isused()
, good, i'd suggest limiting function checking if random key used or not.
function isused($uid) { $stmt=$this->db->query("select * id udid='".$uid."'")or die($this->db->error); if ($stmt->num_rows < 1) { return false; } else { // duplicate key, should return true sure!!! return true; } }
that way, use loop check:
while $obj->isused($ran) { $ran = $obj->generatestrongpassword(); } // put pwd in database after loop!
by way, explain logic has used... check code further inconsistencies... :-)
Comments
Post a Comment