Script Language — PHP
PHP (PHP: Hypertext Preprocessor) is a server-side scripting language designed for web development. Unlike HTML/CSS/JavaScript which run in the browser, PHP runs on the server and generates HTML dynamically. It can process form data, query databases, manage sessions, and produce personalised pages. You'll use XAMPP to run a local Apache server with PHP.
Learning Objectives
- 11.5.3.8 Use a scripting language to process user input and generate dynamic web content
- 11.5.3.6 Demonstrate the use of server-side scripts for handling form data
Conceptual Anchor
The Restaurant Kitchen Analogy
HTML is the menu (what the customer sees). The kitchen is the server running PHP. When a customer (browser) places an order (sends a request), the kitchen (PHP) reads the order, prepares the dish (processes data, queries the database), and sends the finished plate (HTML response) to the table. The customer never sees the kitchen — they only receive the result.
Client-Side vs Server-Side
Client-side (HTML, CSS, JS) = runs in the browser. Server-side (PHP) = runs on the server. The browser never sees PHP code — it only receives the HTML output. This is why you need XAMPP: it provides the Apache server that executes PHP.
Setting Up XAMPP
- Download and install XAMPP from apachefriends.org
- Start the Apache module from the XAMPP Control Panel
- Place your PHP files in
C:\xampp\htdocs\(Windows) or/Applications/XAMPP/htdocs/(Mac) - Access your pages at
http://localhost/yourfile.php - PHP files must have the
.phpextension, not.html
PHP Fundamentals
Basic Syntax
<?php
// PHP code goes between these tags
echo "Hello, World!"; // Output text
echo "<h1>This is HTML from PHP</h1>"; // Output HTML
?>
<!-- PHP embedded in HTML -->
<!DOCTYPE html>
<html>
<body>
<h1>Welcome</h1>
<p>Today is <?php echo date("l, d F Y"); ?></p>
</body>
</html>Variables & Data Types
<?php
// Variables start with $ sign — no declaration needed
$name = "Alice"; // String
$age = 16; // Integer
$gpa = 3.85; // Float
$isStudent = true; // Boolean
// String concatenation uses the dot (.) operator
echo "Name: " . $name . ", Age: " . $age;
// Variable inside double quotes (interpolation)
echo "Hello, $name! You are $age years old.";
// Constants — cannot be changed
define("SCHOOL", "NIS");
echo SCHOOL; // Output: NIS
?>| PHP Feature | Syntax | C++ Equivalent |
|---|---|---|
| Variable | $x = 5; |
int x = 5; |
| Output | echo "text"; |
cout << "text"; |
| Concatenation | "a" . "b" (dot) |
"a" + "b" (not directly) |
| Comparison | == != < > <= >= |
Same |
| Logical | && || ! |
Same |
| Array | $a = [1, 2, 3]; |
int a[] = {1, 2, 3}; |
| Typing | Dynamic (no type declaration) | Static (must declare type) |
Control Structures
<?php
// IF-ELSE
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: C";
}
// FOR loop
for ($i = 1; $i <= 10; $i++) {
echo "$i ";
}
// WHILE loop
$count = 5;
while ($count > 0) {
echo "Countdown: $count <br>";
$count--;
}
// FOREACH (great for arrays)
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "$fruit <br>";
}
// FOREACH with key
$grades = ["Math" => 90, "CS" => 95, "Physics" => 88];
foreach ($grades as $subject => $grade) {
echo "$subject: $grade <br>";
}
?>Functions
<?php
// Define a function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); // Output: Hello, Alice!
// Function with default parameter
function power($base, $exp = 2) {
return $base ** $exp;
}
echo power(3); // Output: 9 (3²)
echo power(2, 5); // Output: 32 (2⁵)
// Useful built-in functions
echo strlen("Hello"); // 5 (string length)
echo strtoupper("hello"); // HELLO
echo str_replace("a", "o", "cat"); // cot
echo count([1, 2, 3, 4]); // 4 (array length)
?>Worked Example — Form Handling
1 Login Form with PHP Processing
login.html — The form (client-side):
<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<h1>Login</h1>
<form action="process_login.php" method="POST">
<label>Username:</label>
<input type="text" name="username" required><br>
<label>Password:</label>
<input type="password" name="password" required><br>
<button type="submit">Log In</button>
</form>
</body>
</html>process_login.php — The processor (server-side):
<?php
// Retrieve form data using $_POST
$username = $_POST["username"];
$password = $_POST["password"];
// Simple validation (in real apps, check against database)
if ($username == "admin" && $password == "secret123") {
echo "<h1>Welcome, $username!</h1>";
echo "<p>Login successful.</p>";
} else {
echo "<h1>Access Denied</h1>";
echo "<p>Invalid username or password.</p>";
echo '<a href="login.html">Try again</a>';
}
?>| Concept | Explanation |
|---|---|
action="..." |
URL of the PHP file that processes the form |
method="POST" |
Send data in HTTP body (hidden). GET sends data in the URL (visible)
|
name="username" |
The key used to access this field in PHP |
$_POST["username"] |
PHP superglobal that retrieves POST data by name |
$_GET["key"] |
Same but for GET method data |
2 Grade Calculator
calculator.php — Form and Processing in one file:
<!DOCTYPE html>
<html>
<head><title>Grade Calculator</title></head>
<body>
<h1>Grade Calculator</h1>
<form method="POST" action="">
<label>Student Name:</label>
<input type="text" name="name" required><br>
<label>Score 1:</label>
<input type="number" name="s1" min="0" max="100"><br>
<label>Score 2:</label>
<input type="number" name="s2" min="0" max="100"><br>
<label>Score 3:</label>
<input type="number" name="s3" min="0" max="100"><br>
<button type="submit" name="calculate">Calculate</button>
</form>
<?php
if (isset($_POST["calculate"])) {
$name = $_POST["name"];
$s1 = (int)$_POST["s1"];
$s2 = (int)$_POST["s2"];
$s3 = (int)$_POST["s3"];
$average = ($s1 + $s2 + $s3) / 3;
if ($average >= 90) { $grade = "A"; }
elseif ($average >= 80) { $grade = "B"; }
elseif ($average >= 70) { $grade = "C"; }
elseif ($average >= 60) { $grade = "D"; }
else { $grade = "F"; }
echo "<h2>Results for $name</h2>";
echo "<p>Scores: $s1, $s2, $s3</p>";
echo "<p>Average: " . number_format($average, 1) . "</p>";
echo "<p>Grade: <strong>$grade</strong></p>";
}
?>
</body>
</html>GET vs POST
| Feature | GET | POST |
|---|---|---|
| Data location | URL: page.php?name=Alice&age=16 |
HTTP body (hidden) |
| Visible to user? | Yes — in address bar | No |
| Data limit | ~2048 characters | No practical limit |
| Bookmarkable? | Yes | No |
| Security | Less secure (data in URL) | More secure |
| Use for | Search, filters, non-sensitive data | Passwords, forms, data changes |
| PHP access | $_GET["key"] |
$_POST["key"] |
Pitfalls & Common Errors
Opening PHP Files Directly
Double-clicking a .php file opens it as text. PHP must run through a server. Always
use http://localhost/file.php via XAMPP, not
file://...
Forgetting the $ Sign
All PHP variables start with $. Writing name = "Alice" instead of
$name = "Alice" causes a fatal error.
Forgetting Semicolons
Every PHP statement must end with ;. Missing it causes a parse error.
Form name Mismatch
If the HTML input is name="user_name" but PHP reads $_POST["username"],
it returns nothing. The name attribute in HTML must exactly match
the key in $_POST.
Using == Instead of ===
== does type coercion: "0" == false is TRUE. === checks
both value AND type: "0" === false is FALSE. Use === for strict
comparison.
Pro-Tips for Exams
Key Exam Points About PHP
- PHP runs on the server — the browser never sees PHP code
- PHP can generate dynamic HTML — different output each time
- Always explain the request-response cycle: browser sends request → server runs PHP → server sends HTML response
- Know the difference between
$_GETand$_POSTand when to use each isset()checks if a variable/form field exists before using it
Graded Tasks
Define: server-side scripting, $_POST, $_GET, echo.
Explain what XAMPP provides.
Draw a diagram showing the request-response cycle between a browser and a PHP server. Label each step.
Create a registration form (HTML) with name, email, age, and gender fields. Write a PHP script that processes the form and displays a personalised welcome page.
Write a PHP script with a form where users enter a number. The script outputs the multiplication table (1–12) for that number in an HTML table.
A student submits a form using GET with a password field. Explain three problems with this approach and how POST solves them.
Build a mini quiz application: a form with 5 multiple-choice questions. The PHP script checks answers, calculates the score, and displays results with correct answers highlighted.