PHP, generate string with format, check against SQL db?
我试图用PHP作为一种在网页中处理的方法,我的典型语言是Java,所以我不熟悉这将如何对产品密钥进行处理。
这基本上是一个过程:
1 2 3 | 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来实现这一点呢?请解释一下我需要做什么,最好的方法是什么。
从以下函数生成随机字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?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请创建唯一的
演示
您可以使用这种方式生成随机数键。
1 2 3 4 5 | echo rk(2)."-".rk(4)."-".rk(4)."-".rk(3); function rk($chars) { $letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; return substr(str_shuffle($letters), 0, $chars); } |
这是一个可能有用的过程!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?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(); ?> |