Home Backend Development PHP Problem PHP implements login database

PHP implements login database

May 07, 2023 am 09:28 AM

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);
Copy after login

}
?>

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="登陆"/>
Copy after login

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 '用户名不存在';
}
Copy after login

}
?>

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

What is the purpose of prepared statements in PHP? What is the purpose of prepared statements in PHP? Mar 20, 2025 pm 04:47 PM

Prepared statements in PHP enhance database security and efficiency by preventing SQL injection and improving query performance through compilation and reuse.Character count: 159

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

See all articles