Skip to lesson content
Web Technologies › Level 21
LEVEL 21 · PHP

PHP Fundamentals

Turn validated form strings into clear calculations and escaped HTML output.

🐘 PHP syntax📨 Form input🛡️ Validation + escaping🧪 Lab + MCQs
01

Learning Objectives

Syntax

Read PHP tags, dollar-prefixed variables and statements.

Values

Use strings, numbers, booleans and arrays deliberately.

Input

Check external field shape and type before conversion.

Output

Escape data for the intended HTML context.

02

PHP Executes in a Supported Runtime

php -v
php -l study-plan.php
php tests.php
php -S 127.0.0.1:8000
# Run these in the folder containing the example files.
03

PHP Tags, Statements and Comments

<?php
// A complete CLI greeting script.
$course = "PHP";
echo "Learning " . $course . "
";
// No closing tag is needed in this PHP-only file.
04

Variables, Types and Strict Comparisons

<?php
$submitted = "2";
var_dump($submitted === 2);  // false
$acceptedDays = (int) $submitted; // after validation
var_dump($acceptedDays === 2); // true
$enabled = true;
$missing = null;
05

Strings, Concatenation and Output

<?php
$topic = "Forms";
echo "Study " . $topic;
echo "
Topic: $topic
";
echo 'Literal variable name: $topic';
06

Operators and Bounded Integer Calculations

<?php
$unitPaise = 12550;
$days = 2;
$totalPaise = $unitPaise * $days; // 25100
$totalINR = (string) intdiv($totalPaise, 100) . "." .
    str_pad((string) ($totalPaise % 100), 2, "0", STR_PAD_LEFT);
echo $totalINR; // 251.00
07

Conditions and Loops

<?php
$errors = ["Choose a course", "Choose 1-5 days"];
foreach ($errors as $error) {
    echo htmlspecialchars($error, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
    echo "
";
}
for ($day = 1; $day <= 5; $day++) {
    echo $day . " ";
}
08

Arrays — Indexed and Associative Data

<?php
$courses = [
    "html" => ["title" => "HTML", "unitPaise" => 12550],
    "css" => ["title" => "CSS", "unitPaise" => 15000]
];
$selected = "html";
if (array_key_exists($selected, $courses)) {
    echo $courses[$selected]["title"];
}
09

Functions Separate Processing from Rendering

<?php
function totalPaise(int $unitPaise, int $days): int
{
    return $unitPaise * $days;
}
$amount = totalPaise(12550, 2);
echo $amount; // 25100
10

GET, POST and PHP Superglobals

Superglobals are predefined arrays available in different scopes. $_GET represents URL query input. $_POST normally contains decoded form data for URL-encoded or multipart POST bodies. $_SERVER provides request and execution information, including the request method in a web environment.

<?php
$method = $_SERVER["REQUEST_METHOD"] ?? "GET";
if ($method === "POST") {
    $days = $_POST["days"] ?? null;
    if (!is_string($days)) {
        // Reject missing or array-valued input before conversion.
    }
}
11

Validate Before Normalizing a Study Plan

Accept one controlled record
Shape

Exactly three scalar string fields.

Label

Trim and check the documented text bound.

Enums and spelling

Known course and a single digit 1–5.

Derive

Convert accepted days and calculate trusted price.

12

Escape Values for HTML Output

<?php
$learner = "Ada <b>";
echo "<p>" . htmlspecialchars(
    $learner, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"
) . "</p>";
// Source: <p>Ada &lt;b&gt;</p>
// Visible text: Ada <b>
13

Trace the Form-to-Response Lifecycle

A study-plan request
Form

Submit learner, course and days.

Processor

Check the method and decoded fields.

Result

Calculate from accepted values and a trusted table.

HTML

Escape values and send a deliberate response.

14

Errors, Headers and Practical Boundaries

Syntax

Check the PHP file before exercising the form.

Validation

Return a useful failure without inventing a quote.

Headers

Set response metadata before writing the body.

Runtime

Verify PHP behavior in its actual environment.

15

Complete PHP Example — A Small Study-Plan Handler

<?php
declare(strict_types=1);

function planEscape(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function processPlan(array $post, string $method, string $mediaType): array
{
    $headers = ['Content-Type' => 'text/html; charset=UTF-8'];
    if ($method === 'GET') {
        return ['status' => 200, 'headers' => $headers,
            'body' => ['message' => 'Form ready. Submit a fictional study plan.']];
    }
    if ($method !== 'POST') {
        $headers['Allow'] = 'GET, POST';
        return ['status' => 405, 'headers' => $headers,
            'body' => ['message' => 'Only GET and POST are supported.']];
    }
    $media = strtolower(trim(explode(';', $mediaType)[0]));
    if ($media !== 'application/x-www-form-urlencoded') {
        return ['status' => 415, 'headers' => $headers,
            'body' => ['message' => 'This example accepts URL-encoded form data.']];
    }
    $keys = array_keys($post);
    sort($keys);
    if ($keys !== ['course', 'days', 'learner']) {
        return ['status' => 400, 'headers' => $headers,
            'body' => ['message' => 'Expected exactly learner, course and days.']];
    }
    foreach (['learner', 'course', 'days'] as $key) {
        if (!is_string($post[$key])) {
            return ['status' => 400, 'headers' => $headers,
                'body' => ['message' => 'Each submitted field must be a string.']];
        }
    }
    $learner = trim($post['learner']);
    $errors = [];
    if (preg_match('/\A.{2,40}\z/u', $learner) !== 1 ||
        preg_match('/[\x00-\x1F\x7F]/', $learner) === 1) {
        $errors[] = 'Learner must contain 2-40 Unicode code points after trim, with no ASCII control characters.';
    }
    $courses = [
        'html' => ['title' => 'HTML', 'unitPaise' => 12550],
        'css' => ['title' => 'CSS', 'unitPaise' => 15000],
        'php' => ['title' => 'PHP', 'unitPaise' => 18000]
    ];
    if (!array_key_exists($post['course'], $courses)) {
        $errors[] = 'Course must be html, css or php.';
    }
    if (preg_match('/\A[1-5]\z/', $post['days']) !== 1) {
        $errors[] = 'Days must be exactly one digit from 1 to 5.';
    }
    if ($errors !== []) {
        return ['status' => 400, 'headers' => $headers,
            'body' => ['message' => 'Form validation failed.', 'errors' => $errors]];
    }
    $days = (int) $post['days'];
    $course = $courses[$post['course']];
    $totalPaise = $course['unitPaise'] * $days;
    $totalINR = (string) intdiv($totalPaise, 100) . '.' .
        str_pad((string) ($totalPaise % 100), 2, '0', STR_PAD_LEFT);
    return ['status' => 200, 'headers' => $headers, 'body' => [
        'message' => 'Study quote calculated; nothing was booked or saved.',
        'accepted' => ['learner' => $learner, 'course' => $course['title'],
            'days' => $days, 'unitPaise' => $course['unitPaise'],
            'totalPaise' => $totalPaise, 'totalINR' => $totalINR]
    ]];
}

function planHtml(array $result): string
{
    $body = $result['body'];
    if (!isset($body['accepted'])) {
        $html = '<p>' . planEscape($body['message']) . '</p>';
        foreach ($body['errors'] ?? [] as $error) {
            $html .= '<p>' . planEscape($error) . '</p>';
        }
        return $html;
    }
    $plan = $body['accepted'];
    return '<h2>Study quote</h2><p>Learner: ' . planEscape($plan['learner']) .
        '</p><p>Course: ' . planEscape($plan['course']) .
        '</p><p>Days: ' . (string) $plan['days'] .
        '</p><p>Total: INR ' . planEscape($plan['totalINR']) . '</p>';
}

// PHP's CLI web server reports "cli-server" here; CLI tests report "cli".
if (PHP_SAPI !== 'cli') {
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    $media = $_SERVER['CONTENT_TYPE'] ?? '';
    $result = processPlan($_POST, $method, $media);
    http_response_code($result['status']);
    foreach ($result['headers'] as $name => $value) {
        header($name . ': ' . $value);
    }
    echo '<!doctype html><html lang="en"><meta charset="UTF-8">';
    echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
    echo '<title>PHP study-plan example</title><body><h1>Study-plan form</h1>';
    echo '<p>Learning example only. No payment, reservation or storage.</p>';
    echo planHtml($result);
    echo '<form action="study-plan.php" method="post">';
    echo '<p><label>Learner <input name="learner" required></label></p>';
    echo '<p><label>Course <select name="course"><option value="html">HTML</option>';
    echo '<option value="css">CSS</option><option value="php">PHP</option></select></label></p>';
    echo '<p><label>Days <select name="days">';
    for ($day = 1; $day <= 5; $day++) {
        echo '<option value="' . $day . '">' . $day . '</option>';
    }
    echo '</select></label></p><button type="submit">Calculate quote</button></form>';
    echo '</body></html>';
}
16

Premium Visualizer — PHP Form Processing

Follow a fixed successful study plan through receiving strings, validation, conversion, calculation and escaped output. The five-stage visualizer keeps the approved controls and styling. This is a teaching trace rather than live PHP execution.

PHP FORM PROCESSING TRACE
Step 1 of 5
STEP 01

Receive decoded form strings

An ordinary URL-encoded POST supplies scalar strings.

$_POST = ["learner" => "Ada", "course" => "html", "days" => "2"]

What is happening?

PHP form input is external data. Check method, media type, exact fields and scalar types.

17

Premium Interactive — Study-Plan Form Demonstration

Use a fictional short label. Try "02", "2.0", "2e0" or a space around "2" to observe rejected representations.

Idle. JavaScript demonstration; PHP is not running in this page.

Simulated decoded form input

No input processed.

Processing stage trace

No trace yet.

Result · status, headers and accepted data

No result yet.

Escaped HTML source · displayed as text

No generated source yet.

Safe preview · DOM text nodes, no PHP execution

No preview yet.

18

Debugging — Separate Syntax, Input and Output

Runtime

PHP source needs PHP execution; a static file upload is not enough.

Shape

Check a missing field or array value before calling string functions.

Representation

Validate the original days string before a cast.

Output

Escape for HTML text and keep response headers before the body.

19

Interview Questions — Flip to Explain

QUESTION

Does a browser execute PHP source like JavaScript?

Click or press Enter to explain
ANSWER

No. A supported PHP runtime executes the server source and sends a response to the browser.

QUESTION

What does the dot operator do in PHP?

Click or press Enter to explain
ANSWER

It concatenates strings. The plus operator is arithmetic rather than PHP string concatenation.

QUESTION

Does strict_types validate HTTP input automatically?

Click or press Enter to explain
ANSWER

No. It concerns scalar type declarations at call boundaries; external fields still need explicit shape, type and value checks.

QUESTION

Why reject days[] before casting?

Click or press Enter to explain
ANSWER

It produces an array-shaped value rather than the required scalar string. String validation and conversion should not run on it.

QUESTION

Why reject "02" even though it can cast to 2?

Click or press Enter to explain
ANSWER

The example accepts exactly one digit from 1 to 5. Conversion happens only after that representation passes validation.

QUESTION

Does $_POST automatically contain a decoded JSON body?

Click or press Enter to explain
ANSWER

No. The normal $_POST form parsing covers URL-encoded or multipart form input; a JSON handler needs a separate raw-body decoding contract.

QUESTION

Why validate and escape separately?

Click or press Enter to explain
ANSWER

Validation checks application meaning. Escaping prepares accepted data for a particular output context, such as HTML text.

QUESTION

Why use 200 for an accepted study quote?

Click or press Enter to explain
ANSWER

It is a successful calculation and display. No booking, payment or persistent resource is created.

20

MCQ Practice — Read the PHP Form Contract

PRACTICE

1. Which opening tag is used in the lesson’s PHP files?

PRACTICE

2. Which prefix begins an ordinary PHP variable?

PRACTICE

3. Which operator concatenates PHP strings?

PRACTICE

4. What does "2" === 2 evaluate to?

PRACTICE

5. What does strlen measure for a PHP string?

PRACTICE

6. Which is an accepted days input in this form contract?

PRACTICE

7. When is days converted to an integer?

PRACTICE

8. What happens to array-valued days?

PRACTICE

9. What is the example’s HTML quote for two days?

PRACTICE

10. What does htmlspecialchars do in this example?

PRACTICE

11. What happens to an extra client price field?

PRACTICE

12. Does passing the browser demonstration prove PHP runtime behavior?

21

Extra Practice — Predict the Form Result

Initial quote

Process Ada/HTML/"2". Expected: 200, numeric days 2, totalPaise 25100 and totalINR "251.00".

Course table

Choose PHP/"5". Expected: 200 and INR 900.00 from the trusted price.

Wrong spelling

Try "02", "2.0", "+2", "2e0", " 2 " and "6". Expected: 400, no accepted quote.

Shape

Try missing days, array-valued days and extra price. Expected: 400 before calculation.

Learner bound

Try a one-code-point label or 41 code points. Expected: 400; a trimmed two-code-point label can pass.

Literal markup

Use Ada <b> as learner. Expected: accepted literal text; source contains &lt;b&gt; and preview has no injected bold node.

Method/type

GET ignores submitted fields and returns ready 200. PUT gives 405; POST with JSON media type gives 415.

Real PHP

  • Run php -l study-plan.php, php tests.php, then the local PHP form.
  • Expected: independently check syntax, algorithm and real request decoding.
22

Quick Revision

Execution: Use a configured PHP runtime.
Blocks: Full PHP tags and clear statement boundaries.
Variables: Dollar prefix and case-sensitive names.
Strings: Concatenate with dot; byte length is not visible-character count.
Types: Strict comparison considers type.
Arrays: Use named records and trusted lookup tables.
Functions: Separate processing, calculation and rendering.
Input: Check decoded external fields independently.
Normalize: Convert only after the representation passes.
Encode: Prepare values for the output context.
23

Glossary — Flip to Learn

TERM

PHP runtime

Click to see meaning
DEFINITION

PHP runtime

The environment that interprets and executes PHP source.

TERM

Superglobal

Click to see meaning
DEFINITION

Superglobal

A predefined PHP variable available across scopes, such as $_POST.

TERM

Scalar form field

Click to see meaning
DEFINITION

Scalar form field

A single string value expected from an ordinary form control, rather than an array.

TERM

Associative array

Click to see meaning
DEFINITION

Associative array

A PHP array using named keys to organize values.

TERM

Concatenation

Click to see meaning
DEFINITION

Concatenation

Combining strings using the PHP dot operator.

TERM

Strict comparison

Click to see meaning
DEFINITION

Strict comparison

A comparison that includes value and type, such as ===.

TERM

Normalization

Click to see meaning
DEFINITION

Normalization

A deliberate conversion of already accepted input into an application representation.

TERM

Output encoding

Click to see meaning
DEFINITION

Output encoding

Preparing data for a particular destination context, such as HTML text.

TERM

Unicode code point

Click to see meaning
DEFINITION

Unicode code point

A Unicode value; it is not always the same as one visible character.

TERM

Request dispatch

Click to see meaning
DEFINITION

Request dispatch

Reading request information, invoking processing and sending a response.

24

Final Challenge — Implement and Inspect a PHP Form

25

Level 21 Complete?

Before marking complete, read the PHP example, explain one valid quote and reproduce type, shape, value and escaping outcomes in the demonstration. Run the separate PHP checks when a PHP environment is available. Completion remains a local study marker.