A PHP Authentication System

A PHP Authentication System




---

# Creating a PHP Login System with User Roles

In this tutorial, we'll walk through the process of building a PHP login system with user roles. User roles allow you to control access to certain parts of your website based on the user's level of privilege. We'll cover user registration, login processes, and how to create secure pages for both regular users and administrators.

## Step 1: Set Up the Database

Start by creating a database and a table to store user information, including their roles.

```sql
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    role VARCHAR(50) NOT NULL DEFAULT 'user'
);
```

## Step 2: Establish Database Connection (`db.php`)

Create a file to handle the database connection. This will be used in other PHP files.

```php
<?php
$servername = "your_server_name";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
```

## Step 3: User Registration (`register.php`)

Implement user registration to allow new users to sign up with a default role.

```php
<?php
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process user registration form data
    // ...
}
?>
```

## Step 4: Login Process (`login_process.php`)

Handle the login process, checking user credentials and assigning roles.

```php
<?php
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process login form data
    // ...
}
?>
```

## Step 5: Secure Pages for Admin and User

Create separate secure pages for administrators and regular users.

- Admin Page (`admin_page.php`)

```php
<?php
session_start();

// Check user role for admin access
// ...
?>
```

- User Page (`user_page.php`)

```php
<?php
session_start();

// Check user role for user access
// ...
?>
```

## Step 6: Logout Script (`logout.php`)

Implement a logout script to destroy the session and log the user out.

```php
<?php
session_start();
session_destroy();
header("Location: login.php");
?>
```

## Conclusion

By following these steps, you've created a basic PHP login system with user roles. This system allows you to manage user access based on their roles, providing a foundation for building more complex web applications with different levels of authorization.

Remember to prioritize security by using secure password hashing, validating user input, and protecting against SQL injection. Always deploy your application on a server with HTTPS to encrypt communication between users and your server.

Feel free to customize and expand upon this tutorial to meet the specific needs of your web development project. Happy coding!


Below is the full code for the PHP login system with user roles. Please note that this code is a basic example and may need further enhancements for production use, such as improving security measures.

### `db.php` - Database Connection

```php
<?php
$servername = "your_server_name";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
```

### `register.php` - User Registration

```php
<?php
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $role = 'user';

    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    $sql = "INSERT INTO users (username, password, role) VALUES ('$username', '$hashed_password', '$role')";
    $conn->query($sql);
}
?>
```

### `login_process.php` - Login Process

```php
<?php
include 'db.php';

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

    $sql = "SELECT * FROM users WHERE username = '$username'";
    $result = $conn->query($sql);

    if ($result->num_rows == 1) {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            session_start();
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];

            if ($user['role'] == 'admin') {
                header("Location: admin_page.php");
            } else {
                header("Location: user_page.php");
            }
        } else {
            header("Location: login.php?error=1");
        }
    } else {
        header("Location: login.php?error=1");
    }
}
?>
```

### `admin_page.php` - Secure Page for Admin

```php
<?php
session_start();

if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
}

echo "Welcome, Admin " . $_SESSION['username'] . "! This is the admin page.";

// Add admin-only content here

echo '<br><a href="logout.php">Logout</a>';
?>
```

### `user_page.php` - Secure Page for User

```php
<?php
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: login.php");
}

echo "Welcome, " . $_SESSION['username'] . "! This is the user page.";

// Add user-specific content here

echo '<br><a href="logout.php">Logout</a>';
?>
```

### `logout.php` - Logout Script

```php
<?php
session_start();
session_destroy();
header("Location: login.php");
?>
```

Make sure to replace placeholders such as `your_server_name`, `your_username`, `your_password`, and `your_database_name` with your actual database details. Additionally, enhance the security measures based on your project requirements.

Contact us for software training, education or development










 

Post a Comment

0 Comments

Me