Home >Backend Development >PHP Problem >PHP implements login database

PHP implements login database

WBOY
WBOYOriginal
2023-05-07 09:28:06977browse

php implements login database

In modern web applications, user authentication is extremely important. A common authentication method is for the user to enter a username and password. After receiving the request, the server will verify whether the information entered by the user is correct. Only after successful verification can the relevant information be successfully accessed. During this process, both parties need to cooperate to achieve normal user authentication. Among them, using a database to store user information on the server side is currently one of the most common implementation methods.

So how to use PHP to implement database user login? This article will explain this process for you.

First of all, we need to make it clear that the user authentication process usually includes the following steps:

  1. The user visits the login page and enters the username and password
  2. The server receives the user name and password entered by the user, and checks whether the user exists in the database
  3. If the user exists, verify whether the password is correct
  4. If the password is correct, return success information to the user , otherwise a failure message is returned.

Below we will introduce step by step how to implement the process of logging into the database.

Step 1: Create a database

Before we start to implement the login function, we need to create a database first. In this article, we use the MySQL database as an example. We first need to install MySQL, then log in to MySQL and create a database named "test".

CREATE DATABASE test;

After the creation is completed, we need to create a user table. In this user table, we need to store the user's username and password.

CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL
);

Step 2: Connect to the database

Before connecting to the database, we need to configure the relevant connection information first. This information includes the user name, password, host name, port, etc. of the database. We can save this configuration information in a separate file and then include this file wherever we need to use it.

Configuration file, such as config.php:

$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "test";
?>

Next we need to connect to the database and select the database we need to use. This process usually requires the use of the mysqli object in PHP.

include('config.php');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
//Detect connection
if ($conn->connect_error) {

die("连接失败: " . $conn->connect_error);

}
?>

Step3: Implement user login

Next we need to implement the user login function. In this example, we need to get the username and password from the form entered by the user. Then pass the username to the database and query whether the user exists. If the user exists, verify that the password is correct. If the password is correct, success information is returned to the user, otherwise failure information is returned.

First, we need to create a simple HTML form to obtain the username and password entered by the user.

<label>用户名:</label>
<input type="text" name="username"/><br/><br/>
<label>密码:</label>
<input type="password" name="password"/><br/><br/>

<input type="submit" value="登陆"/>

The form above combines the username and The password is submitted to the login.php page.

Next, we need to use PHP code to get the username and password entered by the user from the form and pass the username to the database. If the user is found, verify whether the password is correct. If the password is correct, the user information is stored in the session and success information is returned, otherwise failure information is returned.

include('config.php');
// Check whether the form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST") {

// 主动设置编码,防止中文出现乱码
header('Content-type:text/html;charset=utf-8');
$input_username = mysqli_real_escape_string($conn,$_POST['username']);
$input_password = mysqli_real_escape_string($conn,$_POST['password']);
// SQL语句
$sql = "SELECT * FROM users WHERE username = '$input_username'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// 如果查询到了该用户,检查密码是否正确
if($count == 1) {
    if(password_verify($input_password, $row['password'])) {
        // 密码正确,将用户信息存入session中
        session_start();
        $_SESSION["username"] = $row['username'];
        $_SESSION["login_time"] = time();
        echo '登陆成功';
    } else {
        // 密码错误,返回错误信息
        echo '密码错误';
    }
} else {
    // 没有查询到该用户,返回错误信息
    echo '用户名不存在';
}

}
?>

In the above code, the mysqli_real_escape_string function is used to escape strings to avoid SQL injection vulnerabilities. At the same time, we use the password_verify function to verify whether the password entered by the user is correct. This function will compare whether the entered password and the encrypted password are the same.

Step 4: Security considerations

After completing the above steps, we can implement user login. But in practical applications, we also need to consider some security issues, such as: how to ensure the security of user passwords in the database, how to prevent SQL injection, etc.

In order to ensure the security of the user's password in the database, we need to encrypt it. PHP provides many encryption methods, such as MD5, SHA1, Bcrypt, etc. In this article, we use the password_hash and password_verify functions that come with PHP, which allow us to encrypt and decrypt passwords more conveniently while ensuring their security.

At the same time, we also need to consider how to prevent SQL injection vulnerabilities. In the above code, we use the mysqli_real_escape_string function to avoid SQL injection vulnerabilities. At the same time, we can also use PHP PDO to implement database operations. PDO provides a more secure and reliable way to effectively prevent SQL injection attacks.

In this article, we introduce how to use PHP to implement database user login, which includes the process of connecting to the database, obtaining user input, and querying the database. Through the introduction of this article, I believe everyone can understand more clearly how to implement the user login function in PHP, and at the same time be able to notice the security issues involved.

The above is the detailed content of PHP implements login database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn