我尝试使用PHP作为在网页中处理此问题的方法,我的典型语言是java,所以我不熟悉如何对产品密钥进行处理。
这基本上就是这个过程:
1. Generate random string with format XX-XXXX-XXXX-XXX a mix of numbers and letters.
2. Check if it already exists in an SQL database
3. If exists, generate another one and repeat?
那我怎么用PHP做这个呢? 请解释我需要做什么以及最好的方法。
答案 0 :(得分:3)
从以下函数生成随机字符串。
<?php
function randomString() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
$array_lengths = array(2,4,4,3);
foreach($array_lengths as $v){
for ($i = 0; $i < $v; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$pass[] = '-';
}
return rtrim(implode($pass),'-'); //turn the array into a string
}
echo randomString();
?>
<强> SQL 强>
请创建唯一的key
字段,并使用ON DUPLICATE KEY
查询插入/更新数据
答案 1 :(得分:2)
您可以使用这种方式生成随机数字键。
echo rk(2)."-".rk(4)."-".rk(4)."-".rk(3);
function rk($chars) {
$letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
return substr(str_shuffle($letters), 0, $chars);
}
答案 2 :(得分:1)
这是一个可以使用的过程!
<?php
/** The function below was taken from http://stackoverflow.com/questions/853813/how-to-create-a-random-string-using-php **/
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'){
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
/** The function that will do your work is: **/
function theProcess(){
/** Now to inefficiently concatenate your random string together. **/
$theString = randString(2)."-".randString(4)."-".randString(4)."-".randString(3);
echo $theString;
/** Proceed to query your database using MySQLi or PDO, with a query similar to: **/
/** Add your preliminary (connection) code here. **/
$sthandler = $dbhandler->prepare('SELECT 1 FROM products WHERE productKey = ?');
$sthandler->execute(array($theString));
/** Check whether a result is returned from MySQL. **/
if ($sthandler->rowCount() > 0) {
exit("IT EXISTS!");
} else {
theProcess();
}
}
/** Call the function the first time. **/
theProcess();
?>