PHP provides a concrete language for writing that side of an application.
This lesson introduces its syntax, values, arrays, functions and form-processing boundaries, then follows a small study-plan quote from submitted strings to escaped HTML output.
Write clear PHP blocks, distinguish strings from accepted numbers, validate a form independently of browser controls and explain what PHP sends back to a browser.
The interactive lab demonstrates a fixed algorithm in JavaScript; the matching PHP source can run separately in a PHP-enabled environment.
🐘
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
A PHP interpreter evaluates PHP source.
In a web application, the runtime handles a request and produces output such as HTML or JSON.
The browser receives the response; it does not execute the server’s PHP source as browser JavaScript.
Saving a file with a .php extension is not enough.
A host must be configured to execute PHP, or a separate backend must provide it.
Uploading a PHP file into a static frontend folder does not add that runtime.
Keep source and private configuration from being served as public text.
For learning, PHP also has a command-line interface.
You can run a script directly, check its syntax and use the built-in development server.
That development server is intended for local development, not as a public production hosting solution.
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.
With PHP installed, open http://127.0.0.1:8000/study-plan.php after starting the local server.
The downloadable patch contains the example separately from the website upload files.
It does not require changing your existing frontend hosting.
03
🏷️PHP Tags, Statements and Comments
The standard opening tag is <?php.
PHP statements commonly end with a semicolon, while braces delimit blocks such as functions and conditionals.
Comments explain a decision without becoming output.
A PHP file can contain HTML outside PHP blocks, which the runtime sends as output.
A file containing only PHP commonly omits the closing tag to avoid accidental trailing output.
Headers must be sent before response body output.
Use full opening tags rather than relying on a short-tag configuration.
In the examples, the opening tag, variable assignments and echo statements belong to PHP source; the values emitted by echo belong to the response.
<?php
// A complete CLI greeting script.
$course = "PHP";
echo "Learning " . $course . "
";
// No closing tag is needed in this PHP-only file.
Do not confuse a syntax error with a failed form validation.
The interpreter must first understand the program.
A missing semicolon or unmatched brace can prevent the intended handler from running at all.
04
💲Variables, Types and Strict Comparisons
PHP variables begin with a dollar sign.
Names are case-sensitive, so $course and $Course are different variables.
An ordinary assignment stores a value; types include integers, floating-point values, strings, booleans, arrays and null.
The strict comparison operators === and !== consider type as well as value.
Form values arrive as strings in the ordinary scalar form case, so the string "2" is not the same typed value as the integer 2.
Validate the submitted representation before converting it.
Declare(strict_types=1) affects scalar type declarations at call boundaries; it does not automatically validate HTTP input or change every operator into a strict operator.
A cast can produce a number from an unacceptable string, so casting alone is not the form contract.
Avoid depending on loose equality to decide whether an external field is valid, and do not use a successful cast as proof that the original input was acceptable.
05
🔤Strings, Concatenation and Output
PHP uses the dot operator for string concatenation.
Echo emits output, while returning a value from a function makes it available to its caller.
A function can calculate a value without immediately sending anything to the browser.
Double-quoted strings can interpolate variables; single-quoted strings have more limited interpretation.
Choose whichever makes the intended text clear.
The plus operator is for arithmetic, not PHP string concatenation.
A PHP string is a sequence of bytes.
Strlen measures bytes, not a universal count of visible letters.
Our form example uses a UTF-8 regular expression to bound Unicode code points and rejects ASCII control characters; it does not claim to count user-perceived grapheme clusters.
If your application later supports arbitrary prices or very large quantities, review integer range, input rules and formatting again instead of assuming this small contract covers every case.
07
🔀Conditions and Loops
If/elseif/else selects a branch.
An early return can stop a handler after a rejected method or invalid input.
That makes it easier to see why a failure never reaches the calculation.
For and foreach repeat work.
Foreach is convenient for traversing an array of course records or a list of validation errors.
Keep output escaping inside the rendering step rather than assuming array values are safe.
The PHP example gathers independent name, course and day errors after confirming that all three fields are scalar strings.
A missing or array-valued field is rejected earlier because later string functions should not be called on it.
A browser-supplied role or price therefore does not silently become part of the accepted record.
For a real application, document which fields are accepted and which are derived from server data.
09
🧩Functions Separate Processing from Rendering
A function can validate a record, calculate a result or escape text.
Clear parameters and return values make the pieces easier to inspect and test.
Keep a pure calculation separate from the code that sends headers or renders a page.
ProcessPlan in the example receives already decoded form fields, a method and a media type.
It returns a structured result containing status, headers and a body.
PlanHtml turns that accepted result into an escaped HTML fragment.
The dispatch block reads $_POST and $_SERVER, invokes the processor, sends response metadata and outputs a small page.
CLI tests can call the processor without pretending that an HTTPrequest or browser session exists.
<?php
function totalPaise(int $unitPaise, int $days): int
{
return $unitPaise * $days;
}
$amount = totalPaise(12550, 2);
echo $amount; // 25100
Type declarations improve the function interface; they do not replace the processor’s validation of external values.
In the form flow, a string is converted to an integer only after its allowed spelling has been accepted.
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.
A JSONrequest body does not automatically become the same $_POST form array.
A JSON handler would read the raw body through php://input, decode it and validate its own contract.
This example deliberately accepts only application/x-www-form-urlencoded.
Scalar form controls usually produce strings, but bracketed field names can produce arrays.
A crafted days[] input is not the expected scalar duration.
The processor checks is_string before applying a regular expression or cast.
<?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.
}
}
The browser lab shows a simulated already decoded field object.
It is not a PHPrequest parser and does not model duplicate parameter normalization or every possible field-name transformation.
The separate PHP runtime handles actual form decoding.
11
✅Validate Before Normalizing a Study Plan
The exact decoded record is learner, course and days.
All three must be strings.
Learner is trimmed with PHP’s default trim character set, then must contain 2–40 Unicode code points with no ASCII control characters.
Course must be html, css or php.
Days must be exactly one digit from 1 to 5.
Only learner is trimmed.
Days "02", "+2", "2.0", "2e0" and " 2 " are rejected even if a cast could produce an integer.
Once the representation is accepted, convert days to an integer and derive the price from the fixed course table.
Validation and normalization are deliberate application rules.
This short learner label is a demonstration field, not a universal policy for personal names.
Unicode code points and visible characters can differ when combining marks or joined emoji are used.
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.
Failed validation returns 400 without calculating a quote.
GET returns a ready form; unsupported methods return 405 with Allow: GET, POST; an unsupported POST media type returns 415.
A successful quote uses 200 because nothing is booked, paid or stored.
12
🛡️Escape Values for HTML Output
Htmlspecialchars encodes special HTML characters.
The example explicitly uses ENT_QUOTES | ENT_SUBSTITUTE and UTF-8 when placing a learner label into HTML text.
An accepted label such as Ada <b> should be displayed literally rather than creating a bold element.
Escaping does not establish that a value meets the input contract.
Conversely, validating a name’s length does not make it safe to insert as HTML.
Validate at the input boundary and encode for the output context.
HTML text escaping is not SQL protection, JavaScript string encoding or URL validation.
Use parameterized queries for database values and the relevant rules for other destinations.
The study-plan example has no database and never evaluates submitted PHP code.
The browser lab displays both an escaped-source representation and a safe preview built with DOM text nodes.
It does not insert user-provided HTML or execute PHP.
Seeing the source and visible text together makes the encoding boundary easier to inspect.
13
🧭Trace the Form-to-Response Lifecycle
A normal form submission encodes its successful controls, sends the selected method to the action URL and receives a response.
PHP interprets the script on the server, reads the appropriate input arrays and produces the response.
Our example checks method and media type before the form record.
It verifies shape and scalar types, validates fields, calculates the quote and renders escaped output.
A rejected request stops before calculation; the response makes the failed stage visible.
PHP variables in this handler belong to the current execution.
They do not create durable records between independent requests.
Sessions or a database need their own design and lifecycle, as introduced in Level 20.
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.
The lab demonstrates this fixed flow locally.
The real PHP example receives an actual form when run in a configured PHP environment.
Neither version collects a payment, makes a reservation or saves the submitted label.
14
🛠️Errors, Headers and Practical Boundaries
Keep syntax errors, invalid submissions and operational failures separate.
A syntax check helps catch malformed source.
Validation responses help a learner correct an input.
A deployed server needs private diagnostic logging and deliberate handling of unexpected failures.
Header calls and http_response_code belong before body output.
A stray byte before the PHP opening tag or unexpected output from an included file can cause a headers-already-sent problem.
Separating processing from output helps keep this order clear.
Browser restrictions, request-size limits and runtime configuration still matter.
A production handler should bound request bytes before parsing, use an appropriate session and permission design for protected operations, and keep secrets out of public frontend files.
🧾
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.
The demonstration quote does not change server data and is not an authentication system.
It intentionally leaves persistence, payments and protected application actions for separately implemented features.
15
💻Complete PHP Example — A Small Study-Plan Handler
Save the following complete source as study-plan.php in a local PHP example folder.
It includes reusable processing/rendering functions and a web dispatch block.
The supplied tests.php calls those functions from the command line; PHP CLI execution skips the web output block.
Run php -l study-plan.php and php tests.php, then start php -S 127.0.0.1:8000 in that folder and open /study-plan.php.
The example belongs in a PHP-enabled environment; keep it separate from the frontend upload patch.
The code is supplied for inspection and local execution.
The browser exercise below is a JavaScript demonstration of its documented algorithm, not a general PHP interpreter.
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.
✅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
Run the supplied study-plan.php in a local PHP environment.
Keep the exact scalar field contract and trusted course table.
Validate method, media type, shape and values before converting days or calculating a quote.
Escape the accepted learner label when generating HTML text.
Reproduce the valid quote, invalid days spellings, wrong-shaped fields and literal markup case.
Compare the browser demonstration with PHP execution without assuming that one test proves the other runtime.
Add real-request checks for GET, POST and an unsupported method.
Explain the differences between returned values and emitted output, scalar strings and integers, validation and escaping, and a calculated quote and a persistent booking.
Keep the example separate from the static frontenddeployment.
Success criterion: trace accepted external strings into a deliberate PHPresponse and explain each rejected boundary.
Level 22 introduces Java Web Technologies.
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.