js+php实现验证码正确之后,将密码加密后,将相关信息写入数据表user中,完成注册过程的代码
时间: 2024-03-27 14:37:59 浏览: 14
好的,以下是一个简单的实现方式:
前端页面:
```
<form method="post" action="register.php">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<input type="text" name="captcha" placeholder="验证码">
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random();" alt="验证码">
<button type="submit">注册</button>
</form>
```
其中,验证码图片的 `src` 属性指向 `captcha.php`,每次点击图片都会刷新一次验证码。
captcha.php 文件:
```php
<?php
session_start();
header('Content-type: image/png');
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg_color);
$code = '';
$code_length = 4;
$char_set = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$char_set_length = strlen($char_set);
$font_file = 'arial.ttf';
for ($i = 0; $i < $code_length; $i++) {
$char = $char_set[random_int(0, $char_set_length - 1)];
$code .= $char;
$color = imagecolorallocate($image, random_int(0, 200), random_int(0, 200), random_int(0, 200));
imagettftext($image, 20, random_int(-10, 10), $i * 20 + 10, 20, $color, $font_file, $char);
}
$_SESSION['captcha'] = $code;
imagepng($image);
imagedestroy($image);
```
captcha.php 生成一个随机的验证码图片,并将验证码存储在 session 中。
register.php 文件:
```php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$captcha = $_POST['captcha'];
if (strtolower($captcha) !== strtolower($_SESSION['captcha'])) {
echo '验证码错误';
exit;
}
$salt = 'your_salt'; // 自定义盐值
$hashed_password = md5($salt . $password); // 使用md5加密密码
// 连接数据库
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
if (!$conn) {
die('数据库连接失败:' . mysqli_connect_error());
}
// 插入数据
$sql = "INSERT INTO user (username, password) VALUES ('$username', '$hashed_password')";
if (mysqli_query($conn, $sql)) {
echo '注册成功';
} else {
echo '注册失败:' . mysqli_error($conn);
}
mysqli_close($conn);
exit;
}
```
register.php 接收前端发来的数据,检查验证码是否正确,如果正确则将密码加密后写入数据库中。需要注意的是,这里使用了 md5 对密码进行加密,但 md5 不是一种安全的加密方式,建议使用更安全的加密方式,如 bcrypt 或 Argon2。