您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。