通过单击按钮和安全结果生成数据库来生成随机字符

时间:2013-12-27 17:10:56

标签: php mysql character

我需要一个没有JavaScript的简单方法(如果可能的话),生成随机字符(需要通过下拉菜单设置字符数),包括单击按钮的每个UTF-8字符。单击按钮后,需要在我的网站上显示结果,并将结果发送到我的数据库中。

1 个答案:

答案 0 :(得分:1)

<强>表格

<form method="post">
    Password length: <input type="text" name="length" value="12" />
    <button type="submit" name="generate">Generate</button>
</form>

PHP函数生成密码

function getRandomPassword($length=12, $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789!@#$%^&*()_-=+;:,.?"){
    return substr(str_shuffle($chars),0,$length);
}

PHP将密码保存到数据库

function savePasswordToDatabase($password, $dbh){
  // First we prepare our query
  $stmt = $dbh->prepare("INSERT INTO tablenamehere (`fieldnamehere`) VALUES (:password)");

  // We bind values to our prepared query
  $stmt->bindParam(':password',$password);

  // We execute our query
  $stmt->execute();
}

连接到数据库我把它放在这里,所以你可以使用相同的连接进行多次查询

$dbh = new PDO('mysql:host=HOST_HERE;dbname=DATABASENAME_HERE', 'USERNAME_HERE', 'PASSWORD_HERE');

PHP Catch表单提交

if (isset($_POST['generate'])) {
    $length = (int)$_POST['length'];
    if ($length < 6) $length = 6;
    $randomPassword = getRandomPassword($length);
    savePasswordToDatabase($randomPassword, $dbh);
    echo "Password is: {$randomPassword}";
}

基本上是最终结果

<?php

function getRandomPassword($length=12, $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789!@#$%^&*()_-=+;:,.?"){
    return substr(str_shuffle($chars),0,$length);
}

function savePasswordToDatabase($password, $dbh){
  // First we prepare our query
  $stmt = $dbh->prepare("INSERT INTO tablenamehere (`fieldnamehere`) VALUES (:password)");

  // We bind values to our prepared query
  $stmt->bindParam(':password',$password);

  // We execute our query
  $stmt->execute();
}

$dbh = new PDO('mysql:host=HOST_HERE;dbname=DATABASENAME_HERE', 'USERNAME_HERE', 'PASSWORD_HERE');
?>
<html>
<body>
    <form method="post">
        Password length: <input type="text" name="length" value="12" />
        <button type="submit" name="generate">Generate</button>
    </form>
</body>
</html>

<?php 
if (isset($_POST['generate'])) {
    $length = (int)$_POST['length'];
    if ($length < 6) $length = 6;
    $randomPassword = getRandomPassword($length);
    savePasswordToDatabase($randomPassword, $dbh);
    echo "Password is: {$randomPassword}";
}
?>