PHP Fundamentals & Server Setup
                CMU529: Advanced Web Development - Session 4
                Birmingham Newman University
                Lecturer: James Williams
                Introduction to server-side programming with PHP
                3-hour session • 26 slides • 2 interactive tasks
                
                    Session Timeline:
                    
                        - 10 min: Registration & waiting
 
                        - 20 min: Opening slides
 
                        - 45 min: Task 1
 
                        - 15 min: Break/Catch up
 
                        - 20 min: Secondary slides
 
                        - 45 min: Task 2
 
                        - Remaining: Self-study
 
                    
                 
            
            
            
                Learning Objectives
                
                    - Understand PHP basics and server-side programming
 
                    - Set up a local development environment with XAMPP
 
                    - Learn PHP syntax, variables, and data types
 
                    - Create basic PHP scripts and functions
 
                    - Understand PHP's role in web development
 
                    - Build simple dynamic web pages
 
                
            
            
            
                What is PHP?
                
                    PHP (Hypertext Preprocessor) is a server-side scripting
                    language designed for web development
                
                
                    - Open-source and free to use
 
                    - Runs on web servers (Apache, Nginx)
 
                    - Processes code on the server before sending to browser
 
                    - Can generate dynamic HTML content
 
                    - Integrates with databases (MySQL, PostgreSQL)
 
                    - Widely used in web development
 
                
                
                    PHP Processing Flow
                    Request: Browser → Server
                    Process: Server → PHP Engine
                    Response: PHP → HTML → Browser
                 
                
                
                    Watch: PHP Fundamentals Explained
                    
                        
                    
                    
                        Comprehensive introduction to PHP - the server-side programming language
                    
                 
            
            
            
                PHP vs Client-side Languages
                
                    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
                
            
            
            
                Setting Up XAMPP
                
                    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/
                
                
                    - XAMPP provides Apache, MySQL, PHP, and phpMyAdmin
 
                    - All-in-one package for local development
 
                    - No complex configuration required
 
                    - Perfect for learning and development
 
                
            
            
            
                Basic PHP Syntax
                
                    <?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 code is enclosed in 
<?php ?> tags 
                    - Statements end with semicolons
 
                    - Variables start with 
$ symbol 
                    - Comments use 
//, /* */, or # 
                
            
            
            
                PHP Variables
                
                    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);
                    ?>
                
                
                    - Variables are dynamically typed
 
                    - No need to declare data type
 
                    - Case-sensitive names
 
                    - Must start with letter or underscore
 
                
            
            
            
                PHP Data Types
                
                    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;
                
            
            
            
                PHP Arrays
                
                    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
                      ]
                    ];
                
            
            
            
                PHP Functions
                
                    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);
                
            
            
            
                PHP Control Structures
                
                    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";
                    }
                
            
            
            
                PHP Loops
                
                    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>";
                            }
                
            
            
            
                PHP and HTML Integration
                
                    <!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>
                
            
            
            
                PHP Form Processing
                
                    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>";
                    }
                    ?>
                
            
            
            
                Task 1: Basic PHP Development
                
                    Instructions:
                    
                        - Set up XAMPP and start Apache service
 
                        - Create a new project folder in htdocs directory
 
                        - Create PHP files with the following:
 
                        
                            - Basic PHP syntax and variables
 
                            - Arrays and loops
 
                            - Functions with parameters
 
                            - HTML integration
 
                            - Simple form processing
 
                        
                        - Test all files through localhost
 
                        - Create a simple product catalog page
 
                    
                    Time: 45 minutes
                    This task will help you understand PHP basics and server setup
                 
            
            
            
                Break Time
                
                    15 Minutes
                    Take a break, ask questions, or catch up on the previous task.
                    Next: Secondary slides and Task 2
                 
            
            
            
                PHP Superglobals
                
                    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"];
                
            
            
            
                PHP Error Handling
                
                    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);
                
            
            
            
                PHP Security Basics
                
                    - Input Validation: Always validate user input
 
                    - SQL Injection: Use prepared statements
 
                    - XSS Prevention: Escape output with htmlspecialchars()
 
                    - CSRF Protection: Use tokens for forms
 
                    - File Upload Security: Validate file types and sizes
 
                
                
                    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
                    }
                
            
            
            
                PHP File Operations
                
                    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";
                    }
                
            
            
            
                PHP Include and Require
                
                    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>";
                    ?>
                
            
            
            
                PHP Sessions
                
                    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();
                
            
            
            
                PHP Best Practices
                
                    - Code Organization: Use meaningful file and folder names
                    
 
                    - Comments: Document your code properly
 
                    - Naming Conventions: Use consistent naming (camelCase,
                        snake_case)
 
                    - Error Handling: Always handle errors gracefully
 
                    - Security: Never trust user input
 
                    - Performance: Optimize database queries and loops
 
                
                
                    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";
                    }
                
            
            
            
                Task 2: E-commerce PHP Foundation
                
                    Instructions:
                    
                        - Create a basic e-commerce PHP application with:
 
                        
                            - Product listing page with PHP arrays
 
                            - Product detail page with URL parameters
 
                            - Contact form with validation
 
                            - Session-based shopping cart
 
                            - Simple user authentication system
 
                        
                        - Implement proper error handling
 
                        - Use include/require for code organization
 
                        - Add security measures (input validation, XSS prevention)
 
                        - Test all functionality thoroughly
 
                    
                    Time: 45 minutes
                    This task will help you build a foundation for e-commerce PHP
                            development
                 
            
            
            
                Session Summary
                
                    - PHP is a powerful server-side scripting language
 
                    - XAMPP provides a complete local development environment
 
                    - PHP integrates seamlessly with HTML
 
                    - Proper error handling and security are essential
 
                    - Sessions enable user state management
 
                    - Code organization and best practices improve maintainability
 
                
                
                    Next Session:
                    PHP Forms & Data Processing - Advanced form handling and validation