用户认证是一种标准的安全机制,它允许被识别的用户访问任何数字应用程序或网站。它严格防止身份不明的用户访问网络或移动应用程序。
我们在日常生活中使用 Facebook、Twitter、Gmail 等数字产品,我们几乎熟悉用户注册和登录机制。您可以在登录这些应用程序之前创建一个帐户,这样您就可以使用它们的功能。
在本文中,我们将重点介绍使用 PHP 和 MySQL 构建完整的登录和注册系统所需的一些核心功能。
在开始创建安全的 PHP 8 登录和用户注册系统之前,您必须使用MAMP或XAMPP设置本地 Web 服务器。
您还可以按照本教程在 Mac 上设置 MySQL 并在终端应用程序中配置 MySQL。
打开MAMP或XAMPP并启动您的 Web 服务器,然后转到htdocs文件夹并创建以下文件夹和文件,这些文件夹和文件对于开发我们的用户身份验证系统至关重要。
- \-- php-user-authentication
- |-- config
- |--- db.php
- |-- controllers
- |--- login.php
- |--- register.php
- |--- user_activation.php
- |-- css
- |--- style.css
- |-- lib
- |--- 3rd party plugins
- |-- dashboard.php
- |-- header.php
- |-- index.php
- |-- logout.php
- |-- signup.php
- |-- user_verification.php
我们的本地 Web 服务器已启动并正在运行,请转到PHPMyAdmin。
首先创建数据库`your_database_name`。
`table_name`在 MySQL 数据库中创建表。
您可以手动创建列,甚至可以从SQL选项卡执行以下 sql 脚本来创建具有以下值的列。
- CREATE TABLE `users` (
- `id` int(11) NOT NULL,
- `firstname` varchar(100) NOT NULL,
- `lastname` varchar(100) NOT NULL,
- `email` varchar(50) NOT NULL,
- `mobilenumber` varchar(50) NOT NULL,
- `password` varchar(255) NOT NULL,
- `token` varchar(255) NOT NULL,
- `is_active` enum('0','1') NOT NULL,
- `date_time` date NOT NULL
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在config/db.php文件中添加以下代码。
-
- // Enable us to use Headers
- ob_start();
- // Set sessions
- if(!isset($_SESSION)) {
- session_start();
- }
- $hostname = "localhost";
- $username = "phpdemo";
- $password = "4Mu99BhzK8dr4vF1";
- $dbname = "positronx_db";
-
- $connection = mysqli_connect($hostname, $username, $password, $dbname) or die("Database connection not established.")
- ?>
ob_start()方法密切关注输出缓冲并允许我们使用 Header。
$_SESSION允许我们保存可以在 PHP 应用程序中使用的数据,只要浏览器窗口打开,会话就处于活动状态。
要设计用户注册和登录表单 UI,我们使用 Bootstrap 4,在 HTML 布局的头部添加 Bootstrap CSS、JavaScript 和 jQuery 链接。
在signup.php中添加以下代码。
- "en">
- "utf-8">
- "viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
- "stylesheet" href="./css/style.css">
-
PHP User Registration System Example -
-
-
- class="App">
- <div class="vertical-center">
- <div class="inner-block">
- <form action="" method="post">
- <h3>Registerh3>
- <div class="form-group">
- <label>First namelabel>
- <input type="text" class="form-control" name="firstname" id="firstName" />
- div>
- <div class="form-group">
- <label>Last namelabel>
- <input type="text" class="form-control" name="lastname" id="lastName" />
- div>
- <div class="form-group">
- <label>Emaillabel>
- <input type="email" class="form-control" name="email" id="email" />
- div>
- <div class="form-group">
- <label>Mobilelabel>
- <input type="text" class="form-control" name="mobilenumber" id="mobilenumber" />
- div>
- <div class="form-group">
- <label>Passwordlabel>
- <input type="password" class="form-control" name="password" id="password" />
- div>
- <button type="submit" name="submit" id="submit" class="btn btn-outline-primary btn-lg btn-block">
- Sign up
- button>
- form>
- div>
- div>
- div>
- body>
- html>
标记
复制
在index.php中添加以下代码以创建登录表单布局。
- "en">
- "utf-8">
- "viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
- "stylesheet" href="css/style.css">
-
PHP Login System -
-
-
-
- class="App">
- <div class="vertical-center">
- <div class="inner-block">
- <form action="" method="post">
- <h3>Loginh3>
- <div class="form-group">
- <label>Emaillabel>
- <input type="email" class="form-control" name="email_signin" id="email_signin" />
- div>
- <div class="form-group">
- <label>Passwordlabel>
- <input type="password" class="form-control" name="password_signin" id="password_signin" />
- div>
- <button type="submit" name="login" id="sign_in"
- class="btn btn-outline-primary btn-lg btn-block">Sign
- inbutton>
- form>
- div>
- div>
- div>
- body>
- html>
标记
复制
要在 PHP 用户身份验证应用程序中添加样式,请转到css/style.css并添加以下代码。
- * {
- box-sizing: border-box;
- }
- body {
- font-weight: 400;
- background-color: #EEEFF4;
- }
- body,
- html,
- .App,
- .vertical-center {
- width: 100%;
- height: 100%;
- }
- .navbar {
- background: #1833FF !important;
- width: 100%;
- }
- .btn-outline-primary {
- border-color: #1833FF;
- color: #1833FF;
- }
- .btn-outline-primary:hover {
- background-color: #1833FF;
- color: #ffffff;
- }
- .vertical-center {
- display: flex;
- text-align: left;
- justify-content: center;
- flex-direction: column;
- }
- .inner-block {
- width: 450px;
- margin: auto;
- background: #ffffff;
- box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2);
- padding: 40px 55px 45px 55px;
- transition: all .3s;
- border-radius: 20px;
- }
- .vertical-center .form-control:focus {
- border-color: #2554FF;
- box-shadow: none;
- }
- .vertical-center h3 {
- text-align: center;
- margin: 0;
- line-height: 1;
- padding-bottom: 20px;
- }
- label {
- font-weight: 500;
- }
CSS
复制

建立用户注册系统
要创建一个安全的用户注册系统,我们需要进入controllers/register.php文件并将以下代码放入其中。
-
- // Database connection
- include('config/db.php');
- // Swiftmailer lib
- require_once './lib/vendor/autoload.php';
-
- // Error & success messages
- global $success_msg, $email_exist, $f_NameErr, $l_NameErr, $_emailErr, $_mobileErr, $_passwordErr;
- global $fNameEmptyErr, $lNameEmptyErr, $emailEmptyErr, $mobileEmptyErr, $passwordEmptyErr, $email_verify_err, $email_verify_success;
-
- // Set empty form vars for validation mapping
- $_first_name = $_last_name = $_email = $_mobile_number = $_password = "";
- if(isset($_POST["submit"])) {
- $firstname = $_POST["firstname"];
- $lastname = $_POST["lastname"];
- $email = $_POST["email"];
- $mobilenumber = $_POST["mobilenumber"];
- $password = $_POST["password"];
- // check if email already exist
- $email_check_query = mysqli_query($connection, "SELECT * FROM users WHERE email = '{$email}' ");
- $rowCount = mysqli_num_rows($email_check_query);
-
- // PHP validation
- // Verify if form values are not empty
- if(!empty($firstname) && !empty($lastname) && !empty($email) && !empty($mobilenumber) && !empty($password)){
-
- // check if user email already exist
- if($rowCount > 0) {
- $email_exist = '
-
- User with email already exist!
-
- ';
- } else {
- // clean the form data before sending to database
- $_first_name = mysqli_real_escape_string($connection, $firstname);
- $_last_name = mysqli_real_escape_string($connection, $lastname);
- $_email = mysqli_real_escape_string($connection, $email);
- $_mobile_number = mysqli_real_escape_string($connection, $mobilenumber);
- $_password = mysqli_real_escape_string($connection, $password);
- // perform validation
- if(!preg_match("/^[a-zA-Z ]*$/", $_first_name)) {
- $f_NameErr = '
- Only letters and white space allowed.
- ';
- }
- if(!preg_match("/^[a-zA-Z ]*$/", $_last_name)) {
- $l_NameErr = '
- Only letters and white space allowed.
- ';
- }
- if(!filter_var($_email, FILTER_VALIDATE_EMAIL)) {
- $_emailErr = '
- Email format is invalid.
- ';
- }
- if(!preg_match("/^[0-9]{10}+$/", $_mobile_number)) {
- $_mobileErr = '
- Only 10-digit mobile numbers allowed.
- ';
- }
- if(!preg_match("/^(?=.*\d)(?=.*[@#\-_$%^&+=§!\?])(?=.*[a-z])(?=.*[A-Z])[0-9A-Za-z@#\-_$%^&+=§!\?]{6,20}$/", $_password)) {
- $_passwordErr = '
- Password should be between 6 to 20 charcters long, contains atleast one special chacter, lowercase, uppercase and a digit.
- ';
- }
-
- // Store the data in db, if all the preg_match condition met
- if((preg_match("/^[a-zA-Z ]*$/", $_first_name)) && (preg_match("/^[a-zA-Z ]*$/", $_last_name)) &&
- (filter_var($_email, FILTER_VALIDATE_EMAIL)) && (preg_match("/^[0-9]{10}+$/", $_mobile_number)) &&
- (preg_match("/^(?=.*\d)(?=.*[@#\-_$%^&+=§!\?])(?=.*[a-z])(?=.*[A-Z])[0-9A-Za-z@#\-_$%^&+=§!\?]{8,20}$/", $_password))){
- // Generate random activation token
- $token = md5(rand().time());
- // Password hash
- $password_hash = password_hash($password, PASSWORD_BCRYPT);
- // Query
- $sql = "INSERT INTO users (firstname, lastname, email, mobilenumber, password, token, is_active,
- date_time) VALUES ('{$firstname}', '{$lastname}', '{$email}', '{$mobilenumber}', '{$password_hash}',
- '{$token}', '0', now())";
-
- // Create mysql query
- $sqlQuery = mysqli_query($connection, $sql);
-
- if(!$sqlQuery){
- die("MySQL query failed!" . mysqli_error($connection));
- }
- // Send verification email
- if($sqlQuery) {
- $msg = 'Click on the activation link to verify your email.
- $token.'"> Click here to verify email
- ';
- // Create the Transport
- $transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
- ->setUsername('your_email@gmail.com')
- ->setPassword('your_email_password');
- // Create the Mailer using your created Transport
- $mailer = new Swift_Mailer($transport);
- // Create a message
- $message = (new Swift_Message('Please Verify Email Address!'))
- ->setFrom([$email => $firstname . ' ' . $lastname])
- ->setTo($email)
- ->addPart($msg, "text/html")
- ->setBody('Hello! User');
- // Send the message
- $result = $mailer->send($message);
-
- if(!$result){
- $email_verify_err = '
- Verification email coud not be sent!
- ';
- } else {
- $email_verify_success = '
- Verification email has been sent!
- ';
- }
- }
- }
- }
- } else {
- if(empty($firstname)){
- $fNameEmptyErr = '
- First name can not be blank.
- ';
- }
- if(empty($lastname)){
- $lNameEmptyErr = '
- Last name can not be blank.
- ';
- }
- if(empty($email)){
- $emailEmptyErr = '
- Email can not be blank.
- ';
- }
- if(empty($mobilenumber)){
- $mobileEmptyErr = '
- Mobile number can not be blank.
- ';
- }
- if(empty($password)){
- $passwordEmptyErr = '
- Password can not be blank.
- ';
- }
- }
- }
- ?>
PHP
复制
包括处理用户数据的数据库。isset()方法在用户单击提交按钮时检查表单数据,该按钮与我们在注册表单中传递的相同名称属性。
使用 HTTP $_POST[”]方法提取用户数据,例如名字、姓氏、电子邮件、手机号码和密码。
使用 SQL 脚本通过mysqli_query()方法验证用户提供的电子邮件是否已存在于数据库中。
检查表单值是否不为空。
验证用户电子邮件是否已存在,然后使用 Bootstrap 警报消息组件显示错误。我们将错误消息设置为全局变量,以便我们可以将其显示给用户。
mysqli_real_escape_string ()方法在发送到数据库之前清理数据。
preg_match()方法对名称、手机名称和密码进行 PHP 验证。为了验证电子邮件值,我们使用了filter_var()方法。我们包装了错误并将其设置为全局。
我们需要使用md5(rand().time())方法生成随机令牌,以向用户电子邮件 ID 发送验证电子邮件。
为了安全地散列密码,我们使用了password_hash()方法。password_hash() 使用安全的单向散列算法创建一个新的密码散列。
我们需要安装 SwiftMailer php 插件来向用户发送验证邮件,我使用以下 composer 命令来安装 SwiftMailer 库。确保你的开发机器上安装了 composer。
composer require "swiftmailer/swiftmailer:^6.0"
重击
复制
我们需要导入SwiftMailer库并添加 SwiftMailer 脚本,同时定义将发送给用户的电子邮件模板。
现在,我们需要在signup.php文件中实现用户认证逻辑。
- include('./controllers/register.php'); ?>
- "en">
- "utf-8">
- "viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
- "stylesheet" href="./css/style.css">
-
PHP User Registration System Example -
-
-
-
- include('./header.php'); ?>
- class="App">
- <div class="vertical-center">
- <div class="inner-block">
- <form action="" method="post">
- <h3>Registerh3>
- php echo $success_msg; ?>
- php echo $email_exist; ?>
- php echo $email_verify_err; ?>
- php echo $email_verify_success; ?>
- <div class="form-group">
- <label>First namelabel>
- <input type="text" class="form-control" name="firstname" id="firstName" />
- php echo $fNameEmptyErr; ?>
- php echo $f_NameErr; ?>
- div>
- <div class="form-group">
- <label>Last namelabel>
- <input type="text" class="form-control" name="lastname" id="lastName" />
- php echo $l_NameErr; ?>
- php echo $lNameEmptyErr; ?>
- div>
- <div class="form-group">
- <label>Emaillabel>
- <input type="email" class="form-control" name="email" id="email" />
- php echo $_emailErr; ?>
- php echo $emailEmptyErr; ?>
- div>
- <div class="form-group">
- <label>Mobilelabel>
- <input type="text" class="form-control" name="mobilenumber" id="mobilenumber" />
- php echo $_mobileErr; ?>
- php echo $mobileEmptyErr; ?>
- div>
- <div class="form-group">
- <label>Passwordlabel>
- <input type="password" class="form-control" name="password" id="password" />
- php echo $_passwordErr; ?>
- php echo $passwordEmptyErr; ?>
- div>
- <button type="submit" name="submit" id="submit" class="btn btn-outline-primary btn-lg btn-block">Sign up
- button>
- form>
- div>
- div>
- div>
- body>
- html>
PHP
复制
PHP 8 中的用户电子邮件验证脚本
我们在register.php文件中定义了 SwiftMailer 配置,现在实现用户验证脚本发送验证邮件。
在controllers/user_activation.php文件中添加以下代码。
- // Database connection
- include('./config/db.php');
- global $email_verified, $email_already_verified, $activation_error;
- // GET the token = ?token
- if(!empty($_GET['token'])){
- $token = $_GET['token'];
- } else {
- $token = "";
- }
- if($token != "") {
- $sqlQuery = mysqli_query($connection, "SELECT * FROM users WHERE token = '$token' ");
- $countRow = mysqli_num_rows($sqlQuery);
- if($countRow == 1){
- while($rowData = mysqli_fetch_array($sqlQuery)){
- $is_active = $rowData['is_active'];
- if($is_active == 0) {
- $update = mysqli_query($connection, "UPDATE users SET is_active = '1' WHERE token = '$token' ");
- if($update){
- $email_verified = '
- User email successfully verified!
-
- ';
- }
- } else {
- $email_already_verified = '
- User email already verified!
-
- ';
- }
- }
- } else {
- $activation_error = '
- Activation error!
-
- ';
- }
- }
- ?>
PHP
复制
在user_verification.php文件中添加以下代码。
- include('./controllers/user_activation.php'); ?>
- "en">
- "utf-8">
- "viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
- "stylesheet" href="./css/style.css">
-
User Verification -
-
-
- class="container">
- <div class="jumbotron text-center">
- <h1 class="display-4">User Email Verification Demoh1>
- <div class="col-12 mb-5 text-center">
- php echo $email_already_verified; ?>
- php echo $email_verified; ?>
- php echo $activation_error; ?>
- div>
- <p class="lead">If user account is verified then click on the following button to login.p>
- <a class="btn btn-lg btn-success" href="http://localhost:8888/php-user-authentication/index.php"
- >Click to Login
- a>
- div>
- div>
- body>
- html>
PHP
复制

使用 MySQL 构建 PHP 8 登录系统
以下代码仅允许访问已验证其电子邮件地址的用户。未经验证的用户无法在应用程序中访问,我们还将登录用户的数据存储到 PHP Session 中,并借助header(“Location: page_url.php”)方法将登录用户重定向到dashboard.php 页面。
要创建 PHP MySQL 登录系统,请在controllers/login.php文件中添加以下代码。
-
- // Database connection
- include('config/db.php');
- global $wrongPwdErr, $accountNotExistErr, $emailPwdErr, $verificationRequiredErr, $email_empty_err, $pass_empty_err;
- if(isset($_POST['login'])) {
- $email_signin = $_POST['email_signin'];
- $password_signin = $_POST['password_signin'];
- // clean data
- $user_email = filter_var($email_signin, FILTER_SANITIZE_EMAIL);
- $pswd = mysqli_real_escape_string($connection, $password_signin);
- // Query if email exists in db
- $sql = "SELECT * From users WHERE email = '{$email_signin}' ";
- $query = mysqli_query($connection, $sql);
- $rowCount = mysqli_num_rows($query);
- // If query fails, show the reason
- if(!$query){
- die("SQL query failed: " . mysqli_error($connection));
- }
- if(!empty($email_signin) && !empty($password_signin)){
- if(!preg_match("/^(?=.*\d)(?=.*[@#\-_$%^&+=§!\?])(?=.*[a-z])(?=.*[A-Z])[0-9A-Za-z@#\-_$%^&+=§!\?]{6,20}$/", $pswd)) {
- $wrongPwdErr = '
- Password should be between 6 to 20 charcters long, contains atleast one special chacter, lowercase, uppercase and a digit.
- ';
- }
- // Check if email exist
- if($rowCount <= 0) {
- $accountNotExistErr = '
- User account does not exist.
- ';
- } else {
- // Fetch user data and store in php session
- while($row = mysqli_fetch_array($query)) {
- $id = $row['id'];
- $firstname = $row['firstname'];
- $lastname = $row['lastname'];
- $email = $row['email'];
- $mobilenumber = $row['mobilenumber'];
- $pass_word = $row['password'];
- $token = $row['token'];
- $is_active = $row['is_active'];
- }
- // Verify password
- $password = password_verify($password_signin, $pass_word);
- // Allow only verified user
- if($is_active == '1') {
- if($email_signin == $email && $password_signin == $password) {
- header("Location: ./dashboard.php");
-
- $_SESSION['id'] = $id;
- $_SESSION['firstname'] = $firstname;
- $_SESSION['lastname'] = $lastname;
- $_SESSION['email'] = $email;
- $_SESSION['mobilenumber'] = $mobilenumber;
- $_SESSION['token'] = $token;
- } else {
- $emailPwdErr = '
- Either email or password is incorrect.
- ';
- }
- } else {
- $verificationRequiredErr = '
- Account verification is required for login.
- ';
- }
- }
- } else {
- if(empty($email_signin)){
- $email_empty_err = "
- Email not provided.
- ";
- }
-
- if(empty($password_signin)){
- $pass_empty_err = "
- Password not provided.
- ";
- }
- }
- }
- ?>
PHP
复制
要在登录页面中实现登录逻辑,请在controllers/index.php文件中添加以下代码。
- "en">
- "utf-8">
- "viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
- "stylesheet" href="css/style.css">
-
PHP User Registration & Login System Demo -
-
-
-
- include('../php-user-authentication/header.php'); ?>
-
- include('./controllers/login.php'); ?>
-
- class="App">
- <div class="vertical-center">
- <div class="inner-block">
- <form action="" method="post">
- <h3>Loginh3>
- php echo $accountNotExistErr; ?>
- php echo $emailPwdErr; ?>
- php echo $verificationRequiredErr; ?>
- php echo $email_empty_err; ?>
- php echo $pass_empty_err; ?>
- <div class="form-group">
- <label>Emaillabel>
- <input type="email" class="form-control" name="email_signin" id="email_signin" />
- div>
- <div class="form-group">
- <label>Passwordlabel>
- <input type="password" class="form-control" name="password_signin"
- id="password_signin" />
- div>
- <button type="submit" name="login" id="sign_in" class="btn btn-outline-primary btn-lg btn-block">Sign
- inbutton>
- form>
- div>
- div>
- div>
- body>
- html>
PHP
复制
显示登录用户的数据和注销脚本
在dashboard.php中添加以下代码,仅向登录用户显示用户数据。
- include('config/db.php'); ?>
- "en">
- "utf-8">
- "viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
- "stylesheet" href="./css/style.css">
-
PHP User Registration System Example -
-
-
- class="container mt-5">
- <div class="d-flex justify-content-center">
- <div class="card" style="width: 25rem">
- <div class="card-body">
- <h5 class="card-title text-center mb-4">User Profileh5>
- <h6 class="card-subtitle mb-2 text-muted">php echo $_SESSION['firstname']; ?>
- php echo $_SESSION['lastname']; ?>h6>
- <p class="card-text">Email address: php echo $_SESSION['email']; ?>p>
- <p class="card-text">Mobile number: php echo $_SESSION['mobilenumber']; ?>p>
-
- <a class="btn btn-danger btn-block" href="logout.php">Log outa>
- div>
- div>
- div>
- div>
- body>
- html>
PHP
复制
现在,我们需要销毁会话以从用户身份验证系统中注销用户。我们已经将 logout.php 链接传递给仪表板文件中的注销按钮。
打开logout.php并将以下代码放入其中。
-
- session_start();
- session_destroy();
-
- header("Location: http://localhost:8888/php-user-authentication/index.php")
- ;?>
PHP
复制
结论
因此,这是 PHP 8 用户身份验证和登录应用程序。我希望您对我们如何使用 PHP 和 MySQL 进行登录和身份验证系统有基本的了解。我们介绍了一些基本主题,例如向用户发送验证电子邮件、安全地散列密码。
本教程的完整代码可以在GitHub上找到。
-
相关阅读:
小程序分包及分包预下载
Redis客户端通信RESP协议
【技术】Spring Boot 将 Word 转换为 PDF 2.0 版本
使用telnet和ssh登录linux
移动通信网络规划:勘测输出
MangoPapa 的实用小脚本(目录篇)
CVPR 2022 | 美团技术团队精选论文解读
xml schema
聊聊分布式架构01——http通信基础
苹果MacBook电脑应用优化利器CleanMyMac X
-
原文地址:https://blog.csdn.net/allway2/article/details/126423859