在PHP中结合MySQL实现用户认证是一个常见的需求,通常涉及到以下几个步骤:
下面是一个简单的示例代码,展示了如何实现这些步骤:
假设我们有一个名为 users
的表,结构如下:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT); // 使用PHP的password_hash函数
$email = $_POST['email'];
$sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("sss", $username, $password, $email);
$stmt->execute();
echo "New user added successfully";
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<!-- 注册表单 -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
Email: <input type="email" name="email"><br>
<input type="submit" value="Register">
</form>
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if ($user && password_verify($password, $user['password'])) { // 使用PHP的password_verify函数验证密码
$_SESSION['loggedin'] = true;
$_SESSION['id'] = $user['id'];
$_SESSION['username'] = $user['username'];
echo "Login successful";
} else {
echo "Invalid username or password";
}
$stmt->close();
}
?>
<!-- 登录表单 -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
在需要验证用户身份的地方,检查会话是否已登录:
<?php
session_start();
if (!isset($_SESSION['loggedin']) || !$_SESSION['loggedin']) {
header("Location: login.php");
exit();
}
?>
<!-- 需要验证用户身份的内容 -->
<p>Welcome, <?php echo $_SESSION['username']; ?>!</p>
<?php
session_start();
session_destroy();
header("Location: login.php");
exit();
?>
以上示例展示了如何使用PHP和MySQL实现用户注册、登录和会话管理。实际应用中,还需要考虑更多的安全措施,如密码加密、CSRF保护、SQL注入防护等。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。