Aim
To create a simple login form in PHP with server-side validation that checks for empty fields and verifies a username/password pair.
Theory
This is the canonical self-processing form: one PHP file both renders the form and handles its submission. The pattern rests on a few pillars:
- Detecting a submission:
$_SERVER["REQUEST_METHOD"] === "POST"distinguishes a submit from the initial GET that merely displays the page, andisset($_POST["login"])confirms which button was pressed. Credentials travel by POST so they appear in the request body — never in the URL, browser history or server logs, as GET parameters would. - Server-side validation is mandatory: the
requiredattribute on the inputs is only a convenience — anyone can bypass it with DevTools orcurl. The PHP checks (empty()aftertrim()) are the real gate.trim()strips accidental whitespace, and the null-coalescing operator?? ""supplies a default so an absent key never raises a warning. - Output escaping: everything echoed back into HTML passes through
htmlspecialchars(), which converts<,>,&and quotes to entities — the standard defence against XSS (a user typing<script>as a username must never have it executed). - State-driven rendering: PHP computes
$dashDisplay/$loginDisplayand injects them as inlinedisplaystyles, so exactly one of the two panels (dashboard or form) is visible per response.
Requirements
- XAMPP/WAMP with Apache and PHP 8.x
- Code editor (VS Code)
- Browser (Chrome/Edge) — this practical needs a real form POST, so run it under Apache, not the CLI
Procedure
- Start Apache from the XAMPP Control Panel.
- Save the snippet as
p10_login_form.phpinC:\xampp\htdocs\wbplab. - Open
http://localhost/wbplab/p10_login_form.php— the login form appears. - Submit wrong credentials, then the correct pair
rohit/rohit@123, and observe the different responses. - Click Logout on the success panel to return to the form.
Explanation of the Code
- The PHP block at the top runs before any HTML is emitted.
$error,$successand$userstart neutral; they are only changed when a POST with theloginbutton arrives. trim($_POST["username"] ?? "")safely reads and cleans each field. The validation ladder then runs:empty()on either field setsAll fields are required!; the strict comparison$username === "rohit" && $password === "rohit@123"grants access; anything else setsInvalid Username or Password!.$dashDisplayand$loginDisplayare ternaries mapping$successtoblock/none, wired into the two<div>s' inline styles with the short echo tag<?= ... ?>.- The error paragraph renders only inside
<?php if ($error): ?> ... <?php endif; ?>— PHP's alternative syntax for templating. - The form has no
action, so it posts back to the same URL. The Logout button calls the JavaScriptdoLogout(), which only toggles the three elements'displaystyles client-side — no request is sent (session-based logout is Practical 16's job).
Expected Output
On first load the browser shows a centred Login heading, two inputs, a violet Login button and the hint Hint: rohit / rohit@123. Submitting a wrong pair re-renders the form with the red message Invalid Username or Password!; blank fields (with required bypassed) produce All fields are required!. Entering rohit / rohit@123 replaces the form with a green panel reading ✓ Login Successful, Welcome, rohit! and a red Logout button; clicking it flips back to the form and shows ✓ Logged out successfully.
🎯 Viva Questions
- Why must credentials be sent with POST rather than GET? GET puts data in the URL, exposing it in history, bookmarks and server logs; POST carries it in the request body.
- The inputs already have
required— why validate again in PHP? Client-side checks are trivially bypassed; only server-side validation is authoritative. - What does
$_POST["username"] ?? ""guard against? An undefined-index warning when the key is absent —??supplies the fallback. - Why wrap echoed user input in
htmlspecialchars()? To neutralise XSS by converting HTML metacharacters into harmless entities. - How does the page know it is handling a submission?
$_SERVER["REQUEST_METHOD"] === "POST"plusisset($_POST["login"])for the specific button. - What is the main weakness of this practical's logout? It is purely client-side JavaScript — no server state exists, so it is cosmetic; real logout destroys a session (Practical 16).
CO Mapping
CO1, CO2