7 Form Handling And Http Methods

Web Technology II · Unit 7

Form Handling and HTTP Methods

Exam-focused notes for Form Handling and HTTP Methods (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.

Form Handling and HTTP Methods in short

Forms are how users send data to a web application. This chapter shows how to build forms, read the data in PHP, and send a response back.

Form Handling and HTTP Methods: notes

Form elements and input fields

An HTML form collects user input. The action says where to send the data, and the method says how.

<form action="register.php" method="post">
  <label>Name: <input type="text" name="name"></label>
  <label>Email: <input type="email" name="email"></label>
  <label>Password: <input type="password" name="pass"></label>
  <label><input type="radio" name="gender" value="M"> Male</label>
  <label><input type="radio" name="gender" value="F"> Female</label>
  <label><input type="checkbox" name="hobby[]" value="music"> Music</label>
  <select name="city">
    <option value="ktm">Kathmandu</option>
    <option value="pkr">Pokhara</option>
  </select>
  <textarea name="msg"></textarea>
  <input type="submit" value="Send">
</form>
  • Every field needs a name. PHP uses this name as the array key.
  • A group of checkboxes uses name="hobby[]" so PHP receives an array.
  • File upload forms need enctype="multipart/form-data" and method="post".

Form data retrieval

PHP keeps submitted data in superglobal arrays. They are available everywhere without global.

ArrayHolds
$_GETdata sent in the URL
$_POSTdata sent in the request body
$_REQUEST$_GET, $_POST and cookies together
$_FILESuploaded files
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name  = trim($_POST["name"] ?? "");
    $email = filter_var($_POST["email"] ?? "", FILTER_VALIDATE_EMAIL);
    if ($name === "" || !$email) {
        echo "Please fill the form correctly.";
    } else {
        echo "Welcome, " . htmlspecialchars($name);
    }
}

Never trust form data. Check it with isset(), empty() or filter_var(). Escape it with htmlspecialchars() before showing it, and use prepared statements before saving it.

What this unit covers

  • Form data retrieval
  • GET method and query strings
  • POST method and request body
  • GET versus POST comparison
  • Form elements and input fields
  • Form submission and event handling
  • Response headers and redirects

Response headers and redirects

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 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]

Show solved answer

Response headers and a PHP login form

What a response header is

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.

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().

Open this answer on its own page →

GET versus POST comparison

2082 · 5 marks

Differentiate GET method from POST method with examples. [5]

GET and POST are two fundamental HTTP methods used to send requests from a client (browser) to a server. They differ in how data is transmitted and their intended use cases. --- Feature GET Method POST Method --------- Data Transmission Data is appended to the URL as query string Data is sent in ...

Open this answer on its own page →

Form submission and event handling

2079 · 10 marks

Consider you have a login form having username, password fields, login and cancel buttons. Now, write a PHP program for implementing login event. The login should be redirected to home.php upon successful login button event. The cancel button should clear the form field values upon its submission.[10]

Both buttons are submit buttons inside the same form, and each carries its own name. A browser posts only the button that was actually pressed, so the script can ask isset($POST['login']) or isset($POST['cancel']) and know which event it is handling. That is the whole mechanism: PHP has no client...

Open this answer on its own page →

Form data retrieval

2079 · 5 marks

How can you retrieve the form data? Illustrate with example. [5]

When a form is submitted the browser sends the field values to the server, and PHP unpacks them into superglobal arrays that are available in every scope without being declared. Superglobal Holds ------ $GET Values from the query string, so from a form with method="get" or from a link $POST Value...

Open this answer on its own page →

0 · 10 marks

How can you retrieve form data? Write a PHP program to create a form data that will take a Fahrenheit value as input and displays equivalent Celsius value on submit. The Celsius = (5/9)*(Fahrenheit-32).[10]

An HTML form sends its field values to the server when it is submitted, and PHP unpacks them into superglobal arrays, so called because they are available in every scope without being declared. Which array a value lands in depends on the form's method. Superglobal Holds ------

Open this answer on its own page →