James Williams
Birmingham Newman University
jwilliams@staff.newman.ac.uk
3-hour session
Request: Browser → Server
Process: Server → PHP Engine
Response: PHP → HTML → Browser
See Moodle for supporting materials.
PHP (Server-side):
✓ Runs on web server
✓ Processes before page loads
✓ Can access databases
✓ Secure (code not visible)
✓ Generates HTML dynamically
✓ Handles form processing
✓ Session management
✓ File operations
JavaScript (Client-side):
✓ Runs in browser
✓ Processes after page loads
✓ Cannot access databases directly
✗ Code visible to users
✓ Manipulates existing HTML
✓ Handles user interactions
✓ Local storage only
✓ Limited file access
XAMPP Installation Steps:
1. Download XAMPP from apachefriends.org
2. Run installer (Windows/macOS/Linux)
3. Choose installation directory
4. Select components (Apache, MySQL, PHP)
5. Complete installation
6. Start XAMPP Control Panel
7. Start Apache and MySQL services
8. Access http://localhost/phpmyadmin
9. Create project folder in htdocs/
<?php
// This is a PHP comment
echo "Hello, World!";
?>
<?php
/* Multi-line
comment */
$message = "Welcome to PHP";
echo $message;
?>
<?php
# Another comment style
$number = 42;
echo "The answer is: " . $number;
?>
<?php ?> tags$ symbol//, /* */, or #Variable Declaration:
<?php
$name = "John";
$age = 25;
$price = 19.99;
$isActive = true;
$products = ["Apple", "Banana", "Orange"];
echo "Name: " . $name;
echo "Age: " . $age;
echo "Price: $" . $price;
echo "Active: " . ($isActive ? "Yes" : "No");
echo "Products: " . implode(", ", $products);
?>
PHP Data Types:
// String
$name = "John Doe";
$message = 'Hello World';
// Integer
$age = 25;
$count = -10;
// Float
$price = 19.99;
$pi = 3.14159;
// Boolean
$isActive = true;
$isLoggedIn = false;
// Array
$colors = ["red", "green", "blue"];
$user = ["name" => "John", "age" => 25];
// Null
$empty = null;
Array Examples:
// Indexed Array
$products = ["Laptop", "Mouse", "Keyboard"];
echo $products[0]; // Outputs: Laptop
// Associative Array
$user = [
"name" => "John",
"email" => "john@example.com",
"age" => 25
];
echo $user["name"]; // Outputs: John
// Multidimensional Array
$orders = [
[
"id" => 1,
"product" => "Laptop",
"price" => 999.99
],
[
"id" => 2,
"product" => "Mouse",
"price" => 29.99
]
];
Function Examples:
// Basic function
function greet($name) {
return "Hello, " . $name . "!";
}
// Function with default parameter
function calculateTotal($price, $tax = 0.20) {
return $price * (1 + $tax);
}
// Function with multiple parameters
function createUser($name, $email, $age = 18) {
return [
"name" => $name,
"email" => $email,
"age" => $age
];
}
// Using functions
echo greet("John");
echo calculateTotal(100);
$user = createUser("Jane", "jane@example.com", 25);
If Statement:
$age = 18;
if ($age >= 18) {
echo "You are an adult";
} else {
echo "You are a minor";
}
Switch Statement:
$status = "active";
switch ($status) {
case "active":
echo "User is active";
break;
case "inactive":
echo "User is inactive";
break;
default:
echo "Unknown status";
}
Loop Examples:
// For loop
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
// While loop
$count = 0;
while ($count < 3) {
echo "Count: " . $count . "<br>";
$count++;
}
// Foreach loop
$products = ["Laptop", "Mouse", "Keyboard"];
foreach ($products as $product) {
echo "Product: " . $product . "<br>";
}
// Foreach with associative array
$user = ["name" => "John", "age" => 25];
foreach ($user as $key => $value) {
echo $key . ": " . $value . "<br>";
}
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<h1>Welcome to our Store</h1>
<?php
$products = ["Laptop", "Mouse", "Keyboard"];
$currentTime = date("Y-m-d H:i:s");
?>
<p>Current time: <?php echo $currentTime;
?></p>
<h2>Our Products:</h2>
<ul>
<?php foreach ($products as $product): ?>
<li><?php echo $product; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
HTML Form:
<form method="POST" action="process.php">
<label for="name">Name:</label>
<input type="text" name="name"
id="name"><br><br>
<label for="email">Email:</label>
<input type="email" name="email"
id="email"><br><br>
<button type="submit">Submit</button>
</form>
PHP Processing (process.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
}
?>
Time: 45 minutes
This task will help you understand PHP basics and server setup
Take a break, ask questions, or catch up on the previous task.
Next: Secondary slides and Task 2
Common Superglobals:
// $_POST - Form data
$name = $_POST["name"];
// $_GET - URL parameters
$id = $_GET["id"];
// $_SERVER - Server information
$method = $_SERVER["REQUEST_METHOD"];
$url = $_SERVER["REQUEST_URI"];
// $_SESSION - Session data
session_start();
$_SESSION["user_id"] = 123;
// $_COOKIE - Cookie data
$theme = $_COOKIE["theme"];
// $_FILES - File uploads
$uploadedFile = $_FILES["file"];
Error Handling Examples:
// Display errors (development only)
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Try-catch for exceptions
try {
$result = 10 / 0;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Custom error handling
function customErrorHandler($errno, $errstr) {
echo "Error [$errno]: $errstr";
}
set_error_handler("customErrorHandler");
// Error logging
error_log("This is an error message", 0);
Security Examples:
// Input validation
$email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
// XSS prevention
$userInput = "<script>alert('XSS')</script>";
echo htmlspecialchars($userInput);
// File upload validation
$allowedTypes = ["jpg", "png", "gif"];
$fileExtension = strtolower(pathinfo($_FILES["file"]["name"],
PATHINFO_EXTENSION));
if (in_array($fileExtension, $allowedTypes)) {
// Process file
}
File Operations Examples:
// Reading a file
$content = file_get_contents("data.txt");
echo $content;
// Writing to a file
$data = "Hello, World!";
file_put_contents("output.txt", $data);
// Reading file line by line
$handle = fopen("data.txt", "r");
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
// Checking if file exists
if (file_exists("config.php")) {
include "config.php";
}
Include Examples:
// Include file (continues if file not found)
include "header.php";
// Require file (stops if file not found)
require "config.php";
// Include once (prevents multiple inclusion)
include_once "functions.php";
// Require once (prevents multiple inclusion)
require_once "database.php";
// Example structure:
// header.php
<?php
echo "<h1>My Website</h1>";
?>
// footer.php
<?php
echo "<p>© 2024 My Website</p>";
?>
Session Management:
// Start session
session_start();
// Set session variables
$_SESSION["user_id"] = 123;
$_SESSION["username"] = "john_doe";
$_SESSION["logged_in"] = true;
// Access session variables
echo "User ID: " . $_SESSION["user_id"];
echo "Username: " . $_SESSION["username"];
// Check if user is logged in
if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"]) {
echo "Welcome back!";
} else {
echo "Please log in";
}
// Destroy session
session_destroy();
Good Practices Example:
// Good: Clear variable names
$userFirstName = "John";
$userLastName = "Doe";
// Good: Proper error handling
if (!file_exists("config.php")) {
die("Configuration file not found");
}
// Good: Input validation
$email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
if (!$email) {
echo "Invalid email address";
}
Time: 45 minutes
This task will help you build a foundation for e-commerce PHP development
PHP Forms & Data Processing - Advanced form handling and validation