Securing PHP Login Scripts: Best Practices and Code Examples

Learn how to implement secure PHP login scripts to protect your website from potential threats such as SQL injection attacks and unauthorized access. Read about the best practices and see code examples for password encryption, avoiding SQL injection attacks, and proper session management.

The PHP login script is an essential part of any web application that requires user authentication. The PHP login script typically consists of two parts: an HTML form for collecting user credentials (username and password) and a PHP script for processing the form data and verifying the user’s identity.

The HTML form is displayed in the browser, and when the user submits the form, the data is sent to the server where the PHP script is executed. If the user’s credentials are valid, the script logs the user in, and if the credentials are invalid, it returns an error message.

In this example, the PHP script connects to a database to retrieve the user information and verify the user’s identity.

HTML Code (Login Form)

<!DOCTYPE html>
	<title>Login Form</title>
	<form action="login.php" method="post"> <!-- form with method post to submit data -->
		<label for="username">Username:</label>
		<input type="text" name="username" id="username"> <!-- text input for username -->
		<label for="password">Password:</label>
		<input type="password" name="password" id="password"> <!-- password input for password -->
		<input type="submit" value="Submit"> <!-- submit button -->

PHP Code (login.php)

$username = $_POST['username']; // get the username from the form
$password = $_POST['password']; // get the password from the form

$conn = mysqli_connect('host', 'user', 'password', 'database'); //connect to the database

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'"; //select the user with matching username and password
$result = mysqli_query($conn, $query); //execute the query

if (mysqli_num_rows($result) > 0) { //check if the result has rows
    echo "Login successful"; //login successful message
} else {
    echo "Login failed"; //login failed message

mysqli_close($conn); //close the database connection
Note: You need to replace the values of host, user, password, and database with your own database connection details.

Best practices for security in PHP login scripts

Encryption for Storing Passwords

It’s not safe to store passwords in plain text, so it’s best to store hashed passwords instead. Hashing is a one-way encryption process that takes a plain text password and converts it into a fixed-length string of characters. When a user logs in, the script hashes the entered password and compares it to the hashed password stored in the database. If the hashes match, the user is granted access.

Here’s a demo code that demonstrates how to hash a password using the password_hash function:

$password = "password123";
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

echo $hashed_password;

Avoiding SQL Injection Attacks

SQL injection attacks occur when an attacker submits malicious data in an attempt to trick the application into executing unintended SQL commands. To prevent SQL injection attacks, it’s important to use prepared statements and parameterized queries.

Here’s a demo code that demonstrates how to use a prepared statement to prevent SQL injection attacks:

$username = $_POST['username'];
$password = $_POST['password'];

$conn = mysqli_connect('host', 'user', 'password', 'database');

$query = "SELECT * FROM users WHERE username=? AND password=?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
$result = mysqli_stmt_get_result($stmt);

if (mysqli_num_rows($result) > 0) {
    echo "Login successful";
} else {
    echo "Login failed";


Implementing Proper Session Management

Session management is the process of tracking user’s activity on a website. In PHP, sessions are managed using a session ID, which is stored on both the server and the client’s browser as a cookie.

Here’s a demo code that demonstrates how to start a session and store a variable in a session:

$_SESSION['username'] = "user1";

echo "Session started";

It is important to make sure that the session ID is properly protected, otherwise, an attacker could steal the session ID and use it to gain unauthorized access to the user’s session. To protect the session ID, it is recommended to use secure cookies and regenerate the session ID regularly, especially after a successful login.


if (isset($_SESSION['username'])) {
    echo "Welcome, " . $_SESSION['username'];
} else {
    echo "Session not started";


Note: You need to replace the values of host, user, password, and database with your own database connection details.

External resources

PHP Login Script – Tutorial Republic
PHP Login Example – Tutorials point
PHP Login Script – Serpbot


In conclusion, creating a secure PHP login script is an important aspect of web development, as it protects sensitive user information and ensures the privacy and security of website users. By implementing best practices, such as password encryption, proper session management, and protection against SQL injection attacks, you can ensure that your login script is secure and reliable. There are many resources available online, including tutorials, articles, and courses, that can help you create a secure PHP login script for your website. By following the right steps and using the right tools, you can create a login script that is both functional and secure, giving your users peace of mind and ensuring the success of your website.

Latest posts by W3TWEAKS (see all)


Leave a Reply

Your email address will not be published. Required fields are marked *