April 29, 2025 - 23:10
Creating a User Login System with PHP Image
PHP

Creating a User Login System with PHP

Comments

In web applications, managing user sessions and authentication is crucial for ensuring secure access. This guide demonstrates how to build a secure authentication system using PHP.

1. Database Setup

First, create a users table in your MySQL database to store user information:

SQL
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

2. Database Connection (database.php)

PHP
class Database {
    private $host = 'localhost';
    private $db_name = 'user_auth';
    private $username = 'root';
    private $password = '';
    public $conn;

    public function getConnection() {
        $this->conn = null;
        try {
            $this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $exception) {
            echo 'Connection error: ' . $exception->getMessage();
        }
        return $this->conn;
    }
}

3. User Registration (register.php)

The following code handles secure user registration:

PHP
include_once 'database.php';

$database = new Database();
$db = $database->getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $query = 'INSERT INTO users (username, email, password) VALUES (:username, :email, :password)';
    $stmt = $db->prepare($query);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':password', $password);

    if ($stmt->execute()) {
        echo 'Registration successful!';
    } else {
        echo 'Registration failed.';
    }
}

4. User Login (login.php)

The following script verifies user login credentials:

PHP
session_start();
include_once 'database.php';

$database = new Database();
$db = $database->getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'];
    $password = $_POST['password'];

    $query = 'SELECT id, username, password FROM users WHERE email = :email';
    $stmt = $db->prepare($query);
    $stmt->bindParam(':email', $email);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        echo 'Login successful!';
    } else {
        echo 'Invalid email or password.';
    }
}

5. Session Check (session_check.php)

Check whether a user session is active:

PHP
session_start();
if (!isset($_SESSION['user_id'])) {
    echo 'Session not active';
    exit;
} else {
    echo 'Welcome, ' . $_SESSION['username'];
}

6. User Logout (logout.php)

Allow users to securely log out:

PHP
session_start();
session_unset();
session_destroy();
header('Location: login.php');
exit;

7. Security Tips

Enhancing security in your authentication system is vital. Here are some recommendations:

  • Hash passwords: Use password_hash() and password_verify() to securely store passwords.
  • Limit session time: Automatically log users out after inactivity.
  • Add CSRF protection: Use CSRF tokens in your forms.
  • Prevent SQL Injection: Always use bindParam() with prepared statements.
  • Use HTTPS: Encrypt user credentials and secure communication with SSL.

You now have a basic user authentication system including registration, login, logout, and session validation. For more advanced features, consider implementing JWT authentication, OAuth integration, or two-factor authentication (2FA).

Related Articles

Comments ()

No comments yet. Be the first to comment!

Leave a Comment