2082 3

BIT301 ยท 2082 ยท 10 marks

What are the response headers? Create a PHP login form that contains username, password and a login type field defined by dropdown menu. The login type options can be normal or admin. Now, write a function for implementing the login event. The event should be redirected to admin.php if the login cre

What are the response headers? Create a PHP login form that contains username, password and a login type field defined by dropdown menu. The login type options can be normal or admin. Now, write a function for implementing the login event. The event should be redirected to admin.php if the login credentials match and if the login type is admin otherwise it should be redirected to hello.php. Create a proper database connection based on your own assumption.[10]

Web Technology IIChapter 7: Form Handling and HTTP MethodsResponse headers and redirects

Quick answer

A response header is a line of metadata that the server sends back to the browser ahead of the response body, in the header block of the HTTP response. The body says what the page contains, the headers say how the browser should treat it: what media type it is, how long it may be cached, which cookie to store, whether the browser should go somewhere else instead. In PHP every response header is written with the header() function, and because headers travel before the body, header() must be called before a single byte of output (not even a blank line before <?php) has been sent.

Response headers and a PHP login form

What a response header is

The headers a PHP programmer meets most often are these.

HeaderWhat it does
Content-TypeThe media type and charset of the body, for example text/html; charset=UTF-8
LocationSends the browser to another URL, the header behind every PHP redirect
Set-CookieStores a cookie in the browser, including the session cookie
Cache-ControlStates whether and for how long the response may be cached
Content-LengthSize of the body in bytes
WWW-AuthenticateNames the authentication scheme the client must use
ServerIdentifies the server software, usually best suppressed

A redirect is therefore not a special PHP feature, it is just a Location response header plus a 302 status, and the exit after it stops the script from writing a body the browser would ignore.

The database the program assumes

The program assumes a MySQL database mydb with one table of accounts. The password column stores a hash, never the password itself, so it is sized for the 60 character bcrypt output that password_hash() produces, and the role of each account is stored in the table rather than trusted from the form.

CREATE DATABASE mydb CHARACTER SET utf8mb4;

USE mydb;

CREATE TABLE users (
    id            INT AUTO_INCREMENT PRIMARY KEY,
    username      VARCHAR(50) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    role          ENUM('normal', 'admin') NOT NULL DEFAULT 'normal'
);

Accounts are created by a small one off script, so that no plaintext password ever reaches the table:

<?php
require 'db.php';

$stmt = db()->prepare('INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)');
$name = 'admin1';
$hash = password_hash('admin123', PASSWORD_DEFAULT);
$role = 'admin';
$stmt->bind_param('sss', $name, $hash, $role);
$stmt->execute();

The connection

Keeping the connection in one function means the credentials appear once and every page opens the database the same way. mysqli_report() turns driver failures into exceptions so a mistyped query cannot pass silently, and set_charset() makes the connection agree with the table on utf8mb4.

<?php
// db.php
declare(strict_types=1);

function db(): mysqli
{
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = new mysqli('localhost', 'root', '', 'mydb');
    $conn->set_charset('utf8mb4');
    return $conn;
}

The login page

login.php holds both the form and the function that handles the login event. The form posts back to the same file, handleLogin() runs only on a POST, and it returns an error string when the attempt fails so the page below can redisplay the form with a message.

Three points in this function are what earn the marks. The username goes into the query as a bound parameter, so the value can never be read as SQL and injection is impossible. The submitted password is checked with password_verify() against the stored bcrypt hash, so the database holds nothing an attacker could reuse. And the requested login type is checked against the role stored in the row, because a dropdown lives in the browser and a user can post any value they like into it.

<?php
// login.php
session_start();
require 'db.php';

function handleLogin(mysqli $conn): string
{
    $username  = trim($_POST['username'] ?? '');
    $password  = $_POST['password'] ?? '';
    $loginType = $_POST['login_type'] ?? '';

    if ($username === '' || $password === '' || !in_array($loginType, ['normal', 'admin'], true)) {
        return 'Please fill in every field and choose a login type.';
    }

    $stmt = $conn->prepare('SELECT id, username, password_hash, role FROM users WHERE username = ? LIMIT 1');
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    // One message for both failures, so the page never reveals which usernames exist.
    if (!$user || !password_verify($password, $user['password_hash'])) {
        return 'Invalid username or password.';
    }

    if ($loginType === 'admin' && $user['role'] !== 'admin') {
        return 'This account is not an administrator account.';
    }

    // A fresh session id on every login defeats session fixation.
    session_regenerate_id(true);
    $_SESSION['user_id']  = (int) $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['role']     = $user['role'];

    $destination = ($loginType === 'admin') ? 'admin.php' : 'hello.php';
    header("Location: $destination");
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $error = handleLogin(db());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f2f2f2; }
        .login-box { width: 350px; margin: 100px auto; padding: 30px; background: #fff;
                     border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,.2); }
        input, select, button { width: 100%; padding: 10px; margin: 8px 0 16px;
                                box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; }
        button { background: #4CAF50; color: #fff; border: 0; cursor: pointer; }
        .error { color: #c00; }
    </style>
</head>
<body>
<div class="login-box">
    <h2>Login</h2>

    <?php if ($error !== ''): ?>
        <p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p>
    <?php endif; ?>

    <form method="post" action="login.php">
        <label>Username</label>
        <input type="text" name="username"
               value="<?= htmlspecialchars($_POST['username'] ?? '', ENT_QUOTES, 'UTF-8') ?>" required>

        <label>Password</label>
        <input type="password" name="password" required>

        <label>Login type</label>
        <select name="login_type">
            <option value="normal">Normal</option>
            <option value="admin">Admin</option>
        </select>

        <button type="submit">Login</button>
    </form>
</div>
</body>
</html>

The username is echoed back through htmlspecialchars() because it came from the request, and anything that came from the request may contain <script>. The password field is deliberately left empty on a failed attempt: a submitted password is never written back into the page.

The two destination pages

Each destination checks the session for itself. Without that check a user could simply type admin.php in the address bar and reach the page without logging in, because the redirect only tells the browser where to go, it does not protect the target.

<?php
// admin.php
session_start();
if (($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: login.php');
    exit;
}
?>
<h2>Welcome, <?= htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8') ?>. You are signed in as an administrator.</h2>
<a href="logout.php">Logout</a>
<?php
// hello.php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
?>
<h2>Hello, <?= htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8') ?>.</h2>
<a href="logout.php">Logout</a>

Logging out has to undo all three pieces of session state, the array, the cookie and the file on the server:

<?php
// logout.php
session_start();
$_SESSION = [];
if (ini_get('session.use_cookies')) {
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
}
session_destroy();
header('Location: login.php');
exit;

How the request flows

browser posts username + password + login_type to login.php
        |
        v
handleLogin() validates the fields
        |
        v
prepared SELECT fetches the row for that username
        |
   row found and password_verify() passes?
        |                        |
       yes                       no
        |                        |
 role matches the        error string returned,
 requested type?         form redisplayed
        |
       yes
        |
 session_regenerate_id(true), session filled
        |
        v
 Location: admin.php   or   Location: hello.php

In summary

Response headers are the metadata the server sends ahead of the body, and header() is how PHP writes them, which is why the redirect in this program is nothing more than a Location header followed by exit. The login itself is safe because the username is bound into a prepared statement instead of pasted into the query text, the password is verified against a bcrypt hash rather than stored or compared in the clear, the session id is regenerated the moment the user is authenticated, the role comes from the database rather than from the dropdown, and every value printed back into the page passes through htmlspecialchars().

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.