BIT301 Web Technology II

Web Technology IIUnit 511 min read

PHP Functions, Variables & Error Handling: Syntax, Scope & Debugging

Unit 5 of Web Technology II covers PHP’s core building blocks—functions (declaration, parameters, scope), variable handling (global/static), and error management (handlers, logs, suppression)—with real-world form validation examples, database integration, and debugging techniques essential for secure web applications.

Core Concepts

Application LayerDataPresentation LayerDataSession LayerDataTransport LayerSegmentNetwork LayerPacketData Link LayerFramePhysical LayerBits
OSI Model: Packet encapsulation/decapsulation in PHP network requests (e.g., HTTP)

1. Variables in PHP

Variables store data values and are declared without type specification. PHP is loosely typed, meaning variables can hold any data type (string, integer, array, etc.) and change dynamically.

sequenceDiagram
    participant User
    participant PHP
    participant Database
    User->>PHP: POST /login (username=admin, password=123)
    PHP->>PHP: $username = $_POST['username'] (Global)
    PHP->>PHP: $password = $_POST['password'] (Local)
    PHP->>Database: SELECT * FROM users WHERE username='$username'
    Database-->>PHP: Result
    PHP->>PHP: if ($password === $row['password']) { static $loginAttempts = 0; $loginAttempts++; }
Variable scope in a login system (global $POST vs. local $password)

Variable Scope

Variables can be:

  • Local: Accessible only within a function.
  • Global: Accessible anywhere in the script.
  • Static: Retains value between function calls.
stateDiagram-v2
    [*] --> Local: Created inside a function
    Local --> [*]: Destroyed when function exits
    [*] --> Global: Created outside functions
    Global --> [*]: Accessible everywhere
    [*] --> Static: Created inside a function but persists
    Static --> Static: Retains value across calls
    Static --> [*]: Destroyed when script ends

Example: Global vs. Static Variables

<?php
// Global variable
$globalVar = "I am global";

// Function with static variable
function demoStatic() {
    static $staticVar = 0; // Retains value
    $staticVar++;
    echo "Static variable: $staticVar <br>";
}

// Function with local variable
function demoLocal() {
    $localVar = "I am local";
    echo "Local variable: $localVar <br>";
}

demoStatic(); // Output: 1
demoStatic(); // Output: 2 (retains value)
demoLocal();  // Output: "I am local"
echo "Global variable: $globalVar"; // Output: "I am global"
?>

Key Takeaways:

  • Use global keyword to access global variables inside functions.
  • static variables persist between function calls but are not global.
  • Local variables are function-scoped and destroyed after execution.

2. Functions in PHP

Functions are reusable blocks of code that perform specific tasks. They improve code readability and reusability.

Function Declaration

function functionName($param1, $param2) {
    // Code to execute
    return $value; // Optional
}

Example: Calculating Area of a Rectangle

<?php
function calculateArea($length, $width) {
    return $length * $width;
}
$area = calculateArea(5, 10);
echo "Area: $area"; // Output: 50
?>

Passing Parameters by Reference

Use & to pass variables by reference (modifies the original variable).

<?php
function increment(&$num) {
    $num++;
}
$value = 5;
increment($value);
echo $value; // Output: 6 (original variable modified)
?>

Anonymous Functions (Closures)

Functions without a name, often used as callbacks.

<?php
$greet = function($name) {
    echo "Hello, $name!";
};
$greet("Alice"); // Output: Hello, Alice!
?>

Variable Functions

Functions whose names are stored in variables.

<?php
$func = "calculateArea";
$$func(5, 10); // Equivalent to calculateArea(5, 10)
?>

Comparison Table: Anonymous vs. Variable Functions

Feature Anonymous Function Variable Function
Name No name (closure) Name stored in variable
Use Case Callbacks, short-lived tasks Dynamic function calls
Memory Efficiency Higher (no named function) Lower (extra variable)

3. Error Handling in PHP

PHP provides mechanisms to handle errors gracefully, improving debugging and user experience.

Error Reporting

Configure error reporting in php.ini:

  • display_errors: Shows errors on screen (for debugging).
  • error_reporting: Sets error levels (e.g., E_ALL for all errors).
  • log_errors: Logs errors to a file (e.g., /var/log/php_errors.log).

Example: Enabling Error Reporting

<?php
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
?>

Error Suppression

Use @ to suppress errors (not recommended for production).

<?php
$file = @file_get_contents("nonexistent.txt"); // No error shown
?>

Custom Error Handlers

Define functions to handle specific errors.

<?php
function customErrorHandler($errno, $errstr) {
    echo "<b>Error:</b> [$errno] $errstr<br>";
}
set_error_handler("customErrorHandler");
trigger_error("This is a custom error!", E_USER_WARNING);
?>

Error Logging

Log errors to a file for debugging.

<?php
error_log("This is a logged error", 3, "/path/to/error.log");
?>

Example: Login Form with Error Handling

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    $password = $_POST["password"];

    if (empty($username) || empty($password)) {
        trigger_error("Username and password are required!", E_USER_WARNING);
    } else {
        // Validate credentials (e.g., check database)
        echo "Login successful!";
    }
}
?>

In the Real World

  1. eSewa (Nepal)

    • Idea Used: Error Handling and Validation
    • How: When users submit payment details, eSewa validates inputs (e.g., card number, CVV) using PHP functions. If invalid, it triggers custom error messages (e.g., "Invalid card number") instead of crashing. Errors are logged for admin review.
  2. Khalti (Nepal)

    • Idea Used: Static Variables and Session Management
    • How: Khalti’s checkout process uses static variables to retain cart items between pages (e.g., $_SESSION['cart']). This ensures users don’t lose items if they navigate away during payment.
  3. Daraz (Global)

    • Idea Used: Anonymous Functions and AJAX
    • How: Daraz’s "Add to Cart" button uses an anonymous function to dynamically update the cart count via AJAX without reloading the page. The function is passed as a callback to handle the response.
  4. Bank Loan Calculators (Global)

    • Idea Used: Functions with Parameters
    • How: Banks use PHP functions like calculateEMI($principal, $rate, $term) to compute monthly payments. For example, a loan of ₹5,00,000 at 8% for 10 years calls:
      $emi = calculateEMI(500000, 0.08, 120);
      echo "Your EMI is: ₹$emi";
      

Worked Example: Login System with Validation

Scenario: Implement a login form where:

  • Username must be ≥8 characters.
  • Password must be ≥6 characters.
  • Redirect to home.php on success.
<?php
// Database connection (simulated)
$validUsers = ["admin" => "password123", "user" => "pass456"];

// Function to validate login
function validateLogin($username, $password) {
    global $validUsers;
    if (strlen($username) < 8) {
        trigger_error("Username must be at least 8 characters!", E_USER_WARNING);
        return false;
    }
    if (strlen($password) < 6) {
        trigger_error("Password must be at least 6 characters!", E_USER_WARNING);
        return false;
    }
    if (!array_key_exists($username, $validUsers) || $validUsers[$username] !== $password) {
        trigger_error("Invalid username or password!", E_USER_WARNING);
        return false;
    }
    return true;
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    $password = $_POST["password"];
    if (validateLogin($username, $password)) {
        header("Location: home.php");
        exit();
    }
}
?>

<!-- HTML Form -->
<form method="post" action="">
    <label>Username:</label>
    <input type="text" name="username" required><br>
    <label>Password:</label>
    <input type="password" name="password" required><br>
    <input type="submit" value="Login">
</form>

Trace:

  1. User submits form with username="admin123" and password="pass".
  2. validateLogin() checks:
    • Username length (≥8): Pass.
    • Password length (≥6): Pass.
    • Credentials match $validUsers: Fail (triggers error).
  3. Error displayed; user retries.

Database Integration Example

Scenario: Create a PHP form to insert user data into a MySQL table.

erDiagram
    USERS ||--o{ ORDERS : places
    USERS {
        string username PK
        string password
        string email
    }
    ORDERS {
        int id PK
        string product
        float price
        date created_at
        int user_id FK
    }
Database schema for the login system with order validation
<?php
// Database connection
$conn = new mysqli("localhost", "root", "", "users_db");

// Function to insert data
function insertUser($conn, $name, $email, $gender) {
    $stmt = $conn->prepare("INSERT INTO users (name, email, gender) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $name, $email, $gender);
    return $stmt->execute();
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $gender = $_POST["gender"];
    if (insertUser($conn, $name, $email, $gender)) {
        echo "User added successfully!";
    } else {
        echo "Error: " . $conn->error;
    }
}
?>

<!-- HTML Form -->
<form method="post" action="">
    <label>Name:</label>
    <input type="text" name="name" required><br>
    <label>Email:</label>
    <input type="email" name="email" required><br>
    <label>Gender:</label>
    <input type="radio" name="gender" value="male"> Male
    <input type="radio" name="gender" value="female"> Female<br>
    <input type="submit" value="Submit">
</form>

Database Table Design:

erDiagram
    USERS ||--o{ SUBMISSIONS : has
    USERS {
        int id PK
        string name
        string email
        string gender
    }

Exam Tip

  1. Functions:

    • Always declare functions before calling them (unless using anonymous functions).
    • Use return to exit a function early if validation fails.
    • For parameters, distinguish between value (default) and reference (&$var) passing.
  2. Variables:

    • Prefix global variables with $global_ to avoid conflicts.
    • Use static for counters or accumulators in loops.
    • Local variables are not accessible outside their function.
  3. Error Handling:

    • Never use @ in production (it hides critical errors).
    • Prefer try-catch blocks for database operations:
      try {
          $conn->query("SELECT * FROM users");
      } catch (Exception $e) {
          error_log($e->getMessage());
      }
      
    • For exams, show both error display (display_errors) and logging (log_errors) configurations.
  4. Common Pitfalls:

    • Forgetting global keyword for global variables inside functions.
    • Not validating user inputs (always check lengths, formats, and existence).
    • Redirecting after echo (use exit() or die() after header("Location: ...")).
  5. Past Exam Patterns:

    • Login/Signup Forms: Expect validation + database insertion.
    • JSON Handling: Use json_decode() to parse files (e.g., BIT.JSON).
    • Error Logs: Describe php.ini settings (display_errors, error_reporting).

Based on the TU BIT syllabus for Web Technology II (BIT301), unit 5.

Discussion

Loading…