我快到了,但缺少一些东西。我的 PHP 应用程序:
1)用户正在向服务器请求
2)服务器正在生成一个长的唯一字符串并检查数据库中是否存在:如果是则再次生成(直到它不存在),如果否则将其添加到数据库并完成。所有逻辑都应通过单个请求执行,即如果生成的字符串存在,用户不应请求/刷新页面。
我被困在“是”部分。
我的代码(免责声明:我不拥有以下代码的一部分)
<?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 * FROM id WHERE udid='".$uid."'")or die($this->db->error);
while($stmt->num_rows <1) {
$newnum = $this->generateStrongPassword();
$newcheck=$this->db->query("SELECT * FROM id WHERE udid='".$newnum."'")or die($this->db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n"; <- WHAT TO DO IF EXISTS?WHICH PART OF THE SCRIPT SHOULD I RUN AGAIN
} else {
$this->db->query("INSERT INTO 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 as $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);
?>