在PHP中實現用戶登錄功能,通常需要以下幾個步驟:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
<?php
// 連接數據庫
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 注冊新用戶
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
if ($conn->query($sql) === TRUE) {
echo "New user registered successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
<!-- 注冊表單 -->
<form action="" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
<?php
// 連接數據庫
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 用戶登錄
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row["password"])) {
// 登錄成功,跳轉到用戶主頁
header("Location: user_home.php");
} else {
echo "Invalid password";
}
} else {
echo "User not found";
}
}
$conn->close();
?>
<!-- 登錄表單 -->
<form action="" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
<?php
// 連接數據庫
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 檢查用戶是否已登錄
session_start();
if (!isset($_SESSION["loggedin"]) || !$_SESSION["loggedin"]) {
header("Location: login.php");
exit;
}
// 用戶主頁
echo "Welcome, " . $_SESSION["username"];
?>
這只是一個簡單的示例,實際項目中可能需要考慮更多安全性和功能性問題。