Xác thực người dùng rất phổ biến trong ứng dụng web hiện đại. Đó là một cơ chế bảo mật được sử dụng để hạn chế truy cập trái phép vào các khu vực và công cụ chỉ dành cho thành viên trên một trang web
Trong hướng dẫn này, chúng ta sẽ tạo một hệ thống đăng ký và đăng nhập đơn giản bằng cách sử dụng PHP và MySQL. Hướng dẫn này bao gồm hai phần. trong phần đầu tiên, chúng tôi sẽ tạo biểu mẫu đăng ký người dùng và trong phần thứ hai, chúng tôi sẽ tạo biểu mẫu đăng nhập, cũng như trang chào mừng và tập lệnh đăng xuất
Xây dựng hệ thống đăng ký
Trong phần này, chúng ta sẽ xây dựng một hệ thống đăng ký cho phép người dùng tạo tài khoản mới bằng cách điền vào biểu mẫu web. Tuy nhiên, trước tiên chúng ta cần tạo một bảng chứa tất cả dữ liệu người dùng
Bước 1. Tạo bảng cơ sở dữ liệu
Thực hiện truy vấn SQL sau để tạo bảng người dùng bên trong cơ sở dữ liệu MySQL của bạn
CREATE TABLE users [
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR[50] NOT NULL UNIQUE,
password VARCHAR[255] NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
];
Vui lòng xem hướng dẫn về câu lệnh SQL
5 để biết thông tin chi tiết về cú pháp tạo bảng trong hệ thống cơ sở dữ liệu MySQLBước 2. Tạo tệp cấu hình
Sau khi tạo bảng, chúng ta cần tạo tập lệnh PHP để kết nối với máy chủ cơ sở dữ liệu MySQL. Hãy tạo một tệp có tên "config. php" và đặt đoạn mã sau vào bên trong nó
Thí dụ
PDO hướng đối tượng thủ tục
Tải xuốngconnect_error];
}
?>
setAttribute[PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION];
} catch[PDOException $e]{
die["ERROR: Could not connect. " . $e->getMessage[]];
}
?>
Nếu bạn đã tải xuống các ví dụ mã Hướng đối tượng hoặc mã PDO bằng nút tải xuống, vui lòng xóa văn bản "-oo-format" hoặc "-pdo-format" khỏi tên tệp trước khi kiểm tra mã
Ghi chú. Thay thế thông tin đăng nhập theo cài đặt máy chủ MySQL của bạn trước khi kiểm tra mã này, ví dụ: thay tên cơ sở dữ liệu 'demo' bằng tên cơ sở dữ liệu của riêng bạn, thay thế tên người dùng 'root' bằng tên người dùng cơ sở dữ liệu của riêng bạn, chỉ định mật khẩu cơ sở dữ liệu nếu có
Bước 3. Tạo mẫu đăng ký
Hãy tạo một tệp PHP khác "register. php" và đặt mã ví dụ sau vào đó. Mã ví dụ này sẽ tạo một biểu mẫu web cho phép người dùng tự đăng ký
Tập lệnh này cũng sẽ tạo ra lỗi nếu người dùng cố gắng gửi biểu mẫu mà không nhập bất kỳ giá trị nào hoặc nếu tên người dùng do người dùng nhập đã được người dùng khác sử dụng
Thí dụ
PDO hướng đối tượng thủ tục
Tải xuống
Sign Up
Sign Up
Please fill this form to create an account.
" method="post">
Username
Password
Confirm Password
Already have an account? Login here.
prepare[$sql]]{
// Bind variables to the prepared statement as parameters
$stmt->bind_param["s", $param_username];
// Set parameters
$param_username = trim[$_POST["username"]];
// Attempt to execute the prepared statement
if[$stmt->execute[]]{
// store result
$stmt->store_result[];
if[$stmt->num_rows == 1]{
$username_err = "This username is already taken.";
} else{
$username = trim[$_POST["username"]];
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
$stmt->close[];
}
}
// Validate password
if[empty[trim[$_POST["password"]]]]{
$password_err = "Please enter a password.";
} elseif[strlen[trim[$_POST["password"]]] < 6]{
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim[$_POST["password"]];
}
// Validate confirm password
if[empty[trim[$_POST["confirm_password"]]]]{
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim[$_POST["confirm_password"]];
if[empty[$password_err] && [$password != $confirm_password]]{
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if[empty[$username_err] && empty[$password_err] && empty[$confirm_password_err]]{
// Prepare an insert statement
$sql = "INSERT INTO users [username, password] VALUES [?, ?]";
if[$stmt = $mysqli->prepare[$sql]]{
// Bind variables to the prepared statement as parameters
$stmt->bind_param["ss", $param_username, $param_password];
// Set parameters
$param_username = $username;
$param_password = password_hash[$password, PASSWORD_DEFAULT]; // Creates a password hash
// Attempt to execute the prepared statement
if[$stmt->execute[]]{
// Redirect to login page
header["location: login.php"];
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
$stmt->close[];
}
}
// Close connection
$mysqli->close[];
}
?>
Sign Up
Sign Up
Please fill this form to create an account.
" method="post">
Username
Password
Confirm Password
Already have an account? Login here.
prepare[$sql]]{
// Bind variables to the prepared statement as parameters
$stmt->bindParam[":username", $param_username, PDO::PARAM_STR];
// Set parameters
$param_username = trim[$_POST["username"]];
// Attempt to execute the prepared statement
if[$stmt->execute[]]{
if[$stmt->rowCount[] == 1]{
$username_err = "This username is already taken.";
} else{
$username = trim[$_POST["username"]];
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset[$stmt];
}
}
// Validate password
if[empty[trim[$_POST["password"]]]]{
$password_err = "Please enter a password.";
} elseif[strlen[trim[$_POST["password"]]] < 6]{
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim[$_POST["password"]];
}
// Validate confirm password
if[empty[trim[$_POST["confirm_password"]]]]{
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim[$_POST["confirm_password"]];
if[empty[$password_err] && [$password != $confirm_password]]{
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if[empty[$username_err] && empty[$password_err] && empty[$confirm_password_err]]{
// Prepare an insert statement
$sql = "INSERT INTO users [username, password] VALUES [:username, :password]";
if[$stmt = $pdo->prepare[$sql]]{
// Bind variables to the prepared statement as parameters
$stmt->bindParam[":username", $param_username, PDO::PARAM_STR];
$stmt->bindParam[":password", $param_password, PDO::PARAM_STR];
// Set parameters
$param_username = $username;
$param_password = password_hash[$password, PASSWORD_DEFAULT]; // Creates a password hash
// Attempt to execute the prepared statement
if[$stmt->execute[]]{
// Redirect to login page
header["location: login.php"];
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset[$stmt];
}
}
// Close connection
unset[$pdo];
}
?>
Sign Up
Sign Up
Please fill this form to create an account.
" method="post">
Username
Password
Confirm Password
Already have an account? Login here.
— Đầu ra của ví dụ trên [i. e. mẫu đăng ký] sẽ giống như thế này
Sign up now.
prepare[$sql]]{
// Bind variables to the prepared statement as parameters
$stmt->bindParam[":username", $param_username, PDO::PARAM_STR];
// Set parameters
$param_username = trim[$_POST["username"]];
// Attempt to execute the prepared statement
if[$stmt->execute[]]{
// Check if username exists, if yes then verify password
if[$stmt->rowCount[] == 1]{
if[$row = $stmt->fetch[]]{
$id = $row["id"];
$username = $row["username"];
$hashed_password = $row["password"];
if[password_verify[$password, $hashed_password]]{
// Password is correct, so start a new session
session_start[];
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header["location: welcome.php"];
} else{
// Password is not valid, display a generic error message
$login_err = "Invalid username or password.";
}
}
} else{
// Username doesn't exist, display a generic error message
$login_err = "Invalid username or password.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset[$stmt];
}
}
// Close connection
unset[$pdo];
}
?>
Login
Login
Please fill in your credentials to login.
' . $login_err . '';
}
?>
" method="post">
Username
Password
Don't have an account? Sign up now.
— Đầu ra của ví dụ trên [i. e. đăng nhập] sẽ giống như thế này
Bước 2. Tạo trang chào mừng
Đây là mã của "chào mừng" của chúng tôi. php", nơi người dùng được chuyển hướng sau khi đăng nhập thành công
0Nếu dữ liệu đến từ các nguồn bên ngoài như biểu mẫu được điền bởi người dùng ẩn danh, thì có nguy cơ dữ liệu đó có thể chứa tập lệnh độc hại được thụt vào để khởi chạy các cuộc tấn công tập lệnh chéo trang [XSS]. Do đó, bạn phải thoát dữ liệu này bằng cách sử dụng hàm PHP
8 trước khi hiển thị nó trong trình duyệt, để mọi thẻ HTML chứa trong đó trở nên vô hạiVí dụ: sau khi thoát các ký tự đặc biệt, chuỗi
9 trở thànhconnect_error];
}
?>
0 mà trình duyệt không thực thiBước 3. Tạo tập lệnh đăng xuất
Bây giờ, hãy tạo một "đăng xuất. tập tin php". Khi người dùng nhấp vào liên kết đăng xuất hoặc đăng xuất, tập lệnh bên trong tệp này sẽ hủy phiên và chuyển hướng người dùng quay lại trang đăng nhập
Thêm tính năng Đặt lại mật khẩu
Cuối cùng, trong phần này, chúng tôi sẽ thêm tiện ích đặt lại mật khẩu vào hệ thống đăng nhập của chúng tôi. Sử dụng tính năng này, người dùng đã đăng nhập có thể ngay lập tức đặt lại mật khẩu của chính họ cho tài khoản của họ