PHP for Backend Development

Understanding the fundamentals and ecosystem of one of the web's most widespread languages

Introduction to PHP

PHP (PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. Despite the rise of newer backend technologies, PHP remains one of the most popular languages for building web applications, powering approximately 78% of all websites that use a server-side language.

PHP was created by Rasmus Lerdorf in 1994 as a simple set of Common Gateway Interface (CGI) binaries written in C to track visits to his online resume. Since then, it has evolved into a full-fledged programming language, with the current stable version being PHP 8.2 (as of 2025).

timeline title Evolution of PHP 1994 : PHP 1.0 : Personal Home Page Tools 1995 : PHP 2.0 : First public release 1998 : PHP 3.0 : Rewritten from scratch
Added object support 2000 : PHP 4.0 : Zend Engine 1.0
Improved performance 2004 : PHP 5.0 : Zend Engine 2.0
Enhanced OOP 2015 : PHP 7.0 : Zend Engine 3.0
Major performance improvements 2020 : PHP 8.0 : JIT compiler
Union types
Named arguments 2021 : PHP 8.1 : Enumerations
Readonly properties 2022 : PHP 8.2 : Readonly classes
DNF types

Key Characteristics of PHP

A Simple PHP Example

Here's a basic example to illustrate PHP in action:


<!DOCTYPE html>
<html>
<head>
    <title>My First PHP Page</title>
</head>
<body>
    <h1>Hello, World!</h1>
    
    <?php
    // This is a PHP code block
    $currentTime = date("Y-m-d H:i:s");
    echo "<p>The current server time is: $currentTime</p>";
    
    // A simple conditional statement
    $hour = (int)date("H");
    if ($hour < 12) {
        echo "<p>Good morning!</p>";
    } elseif ($hour < 18) {
        echo "<p>Good afternoon!</p>";
    } else {
        echo "<p>Good evening!</p>";
    }
    ?>
    
    <p>This is regular HTML again.</p>
</body>
</html>
        

This example demonstrates how PHP is mixed with HTML. The PHP interpreter processes only the code between <?php and ?> tags, leaving the rest of the HTML untouched.

The Role of PHP in Web Development

Despite the emergence of newer technologies, PHP maintains a significant role in web development due to its simplicity, flexibility, and the massive ecosystem built around it.

PHP's Place in the Web Development Ecosystem

Client Side HTML CSS JavaScript Frontend Frameworks Server Side PHP Node.js Python Java/.NET/Ruby/Go HTTP Request HTTP Response Database

Advantages of PHP

Limitations of PHP

Common Use Cases for PHP

PHP in the Enterprise

Despite its reputation as a language for small projects, PHP powers many large-scale applications and websites:

PHP Basic Syntax and Structure

PHP Tags

PHP code is enclosed between special tags:


<?php
  // PHP code goes here
?>

// Short echo tag (must be enabled in php.ini)
<?= $variable ?>  // Equivalent to <?php echo $variable; ?>
        

Variables and Data Types

PHP variables start with a dollar sign ($) and are loosely typed:


<?php
// Variable declaration
$name = "John";    // String
$age = 30;         // Integer
$height = 1.85;    // Float/Double
$isStudent = true; // Boolean
$hobbies = ["reading", "swimming", "coding"];  // Array
$person = null;    // Null value

// Type casting
$stringNumber = "42";
$actualNumber = (int)$stringNumber;  // Converts to integer
$backToString = (string)$actualNumber;  // Converts back to string

// Variable interpolation in strings
echo "My name is $name and I am $age years old.";  // Works with double quotes
echo 'My name is $name and I am $age years old.';  // Doesn't work with single quotes
echo "My name is {$name} and I am {$age} years old.";  // Curly braces for complex expressions
?>
        

Control Structures

PHP supports standard control structures for conditional logic and loops:


<?php
// Conditional statements
$temperature = 22;

if ($temperature < 0) {
    echo "It's freezing!";
} elseif ($temperature < 20) {
    echo "It's cool.";
} else {
    echo "It's warm.";
}

// Switch statement
$dayOfWeek = date("l");
switch ($dayOfWeek) {
    case "Monday":
        echo "Start of the work week";
        break;
    case "Friday":
        echo "Almost weekend!";
        break;
    case "Saturday":
    case "Sunday":
        echo "It's weekend!";
        break;
    default:
        echo "It's a weekday";
        break;
}

// Loops
// For loop
for ($i = 0; $i < 5; $i++) {
    echo "Iteration number: $i
"; } // While loop $count = 0; while ($count < 5) { echo "Count: $count
"; $count++; } // Do-while loop $x = 0; do { echo "The number is: $x
"; $x++; } while ($x < 5); // Foreach loop (for arrays) $colors = ["red", "green", "blue"]; foreach ($colors as $color) { echo "Color: $color
"; } // Foreach with key and value $person = [ "name" => "John", "age" => 30, "city" => "New York" ]; foreach ($person as $key => $value) { echo "$key: $value
"; } ?>

Functions

Functions in PHP are defined using the function keyword:


<?php
// Basic function
function sayHello($name) {
    return "Hello, $name!";
}

echo sayHello("Alice");  // Outputs: Hello, Alice!

// Function with default parameters
function greet($name, $greeting = "Hello") {
    return "$greeting, $name!";
}

echo greet("Bob");  // Outputs: Hello, Bob!
echo greet("Charlie", "Hi");  // Outputs: Hi, Charlie!

// Variable number of arguments
function sum(...$numbers) {
    return array_sum($numbers);
}

echo sum(1, 2, 3, 4, 5);  // Outputs: 15

// Type declarations (PHP 7+)
function multiply(int $a, int $b): int {
    return $a * $b;
}

echo multiply(5, 3);  // Outputs: 15
?>
        

Arrays

PHP supports both indexed and associative arrays:


<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];
echo $fruits[0];  // Outputs: apple

// Associative array
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];
echo $person["name"];  // Outputs: John

// Multidimensional array
$users = [
    ["name" => "Alice", "email" => "alice@example.com"],
    ["name" => "Bob", "email" => "bob@example.com"]
];
echo $users[1]["email"];  // Outputs: bob@example.com

// Array functions
$numbers = [1, 2, 3, 4, 5];
echo count($numbers);  // Outputs: 5

// Adding elements
$fruits[] = "grape";  // Adds to the end
array_push($fruits, "mango", "pineapple");  // Adds multiple items
array_unshift($fruits, "strawberry");  // Adds to the beginning

// Removing elements
$lastFruit = array_pop($fruits);  // Removes and returns the last element
$firstFruit = array_shift($fruits);  // Removes and returns the first element

// Sorting
sort($fruits);  // Sorts indexed array
asort($person);  // Sorts associative array by value
ksort($person);  // Sorts associative array by key

// Functional operations
$doubled = array_map(function($n) { return $n * 2; }, $numbers);
$even = array_filter($numbers, function($n) { return $n % 2 === 0; });
$sum = array_reduce($numbers, function($carry, $n) { return $carry + $n; }, 0);
?>
        

Object-Oriented Programming

PHP supports object-oriented programming with classes and objects:


<?php
// Class definition
class Person {
    // Properties
    public $name;
    private $age;
    protected $email;
    
    // Constructor
    public function __construct($name, $age, $email) {
        $this->name = $name;
        $this->age = $age;
        $this->email = $email;
    }
    
    // Methods
    public function sayHello() {
        return "Hello, my name is {$this->name}!";
    }
    
    // Getter and setter
    public function getAge() {
        return $this->age;
    }
    
    public function setAge($age) {
        if ($age >= 0 && $age <= 120) {
            $this->age = $age;
        }
    }
}

// Creating an object
$john = new Person("John", 30, "john@example.com");
echo $john->sayHello();  // Outputs: Hello, my name is John!
echo $john->name;  // Accessible (public)
// echo $john->age;  // Error (private)
echo $john->getAge();  // Accessible through getter

// Inheritance
class Student extends Person {
    private $studentId;
    
    public function __construct($name, $age, $email, $studentId) {
        parent::__construct($name, $age, $email);
        $this->studentId = $studentId;
    }
    
    public function getStudentInfo() {
        return "{$this->name} (ID: {$this->studentId})";
    }
}

$alice = new Student("Alice", 20, "alice@example.com", "S12345");
echo $alice->getStudentInfo();  // Outputs: Alice (ID: S12345)
?>
        

PHP in Modern Web Development

The PHP Ecosystem

flowchart TD PHP[PHP Language] --> Frameworks[PHP Frameworks] PHP --> CMS[Content Management
Systems] PHP --> Composer[Package Management
Composer] PHP --> Testing[Testing Tools] PHP --> DevTools[Development Tools] Frameworks --> Laravel[Laravel] Frameworks --> Symfony[Symfony] Frameworks --> CodeIgniter[CodeIgniter] Frameworks --> SlimPHP[Slim PHP] Frameworks --> Yii[Yii] CMS --> WordPress[WordPress] CMS --> Drupal[Drupal] CMS --> Joomla[Joomla] CMS --> Magento[Magento] Composer --> Packages[Packagist
Repository] Testing --> PHPUnit[PHPUnit] Testing --> Behat[Behat] Testing --> PHPStan[PHPStan] DevTools --> Xdebug[Xdebug] DevTools --> PHP_CS[PHP-CS-Fixer] DevTools --> PHPStorm[PhpStorm] style PHP fill:#B91C1C,stroke:#7F1D1D,stroke-width:2px,color:#ffffff style Frameworks fill:#f4a582,stroke:#333,stroke-width:2px style CMS fill:#e9ecef,stroke:#333,stroke-width:2px style Composer fill:#a6d96a,stroke:#333,stroke-width:2px style Testing fill:#fdae61,stroke:#333,stroke-width:2px style DevTools fill:#abd9e9,stroke:#333,stroke-width:2px

Modern PHP Frameworks

Modern PHP development has moved significantly from procedural code to frameworks that implement best practices and design patterns:

PHP and APIs

Modern PHP excels at building APIs for web and mobile applications:


<?php
// Example of a simple REST API endpoint in pure PHP
header('Content-Type: application/json');

// Get HTTP method and route
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'], '/'));

// Connect to database (simplified example)
$pdo = new PDO('mysql:host=localhost;dbname=api_db', 'username', 'password');

// Example resource: users
if ($request[0] === 'users') {
    switch ($method) {
        case 'GET':
            // Get user(s)
            if (isset($request[1])) {
                // Get specific user
                $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
                $stmt->execute([$request[1]]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                echo json_encode($user);
            } else {
                // Get all users
                $stmt = $pdo->query("SELECT * FROM users");
                $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                echo json_encode($users);
            }
            break;
            
        case 'POST':
            // Create new user
            $data = json_decode(file_get_contents('php://input'), true);
            $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
            $stmt->execute([$data['name'], $data['email']]);
            echo json_encode(['id' => $pdo->lastInsertId()]);
            break;
            
        case 'PUT':
            // Update existing user
            $data = json_decode(file_get_contents('php://input'), true);
            $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");
            $stmt->execute([$data['name'], $data['email'], $request[1]]);
            echo json_encode(['success' => true]);
            break;
            
        case 'DELETE':
            // Delete user
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$request[1]]);
            echo json_encode(['success' => true]);
            break;
    }
}
?>
        

With frameworks like Laravel or Slim, API development becomes even more streamlined:


<?php
// Example of a RESTful API in Laravel (routes/api.php)
use App\Http\Controllers\UserController;

Route::get('/users', [UserController::class, 'index']);
Route::get('/users/{id}', [UserController::class, 'show']);
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);
        

Package Management with Composer

Composer has revolutionized PHP development by providing a robust dependency management system:


# Example composer.json file
{
    "name": "vendor/project",
    "description": "Project description",
    "type": "project",
    "require": {
        "php": "^8.1",
        "guzzlehttp/guzzle": "^7.0",
        "monolog/monolog": "^2.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

# Installing dependencies
composer install

# Adding a new package
composer require symfony/console
        

PHP Performance and Optimization

Modern PHP has made significant performance improvements:

Deployment Options

PHP applications can be deployed in various ways:

PHP vs. Other Backend Technologies

Comparison with Node.js

Feature PHP Node.js
Language PHP (server-side scripting) JavaScript (event-driven)
Execution Model Request-based (typically) Event loop (single-threaded, non-blocking)
Learning Curve Lower for beginners Steeper if unfamiliar with callbacks/promises
Use Cases Traditional websites, CMS, e-commerce Real-time applications, APIs, microservices
Performance Good with PHP 7+, especially for I/O-bound operations Excellent for asynchronous operations and concurrent connections
Ecosystem Mature, extensive libraries for web development Rapidly growing, strong in modern JavaScript frameworks

Comparison with Python

Feature PHP Python
Primary Focus Web development General-purpose programming
Web Frameworks Laravel, Symfony, CodeIgniter Django, Flask, FastAPI
Syntax C-like syntax Whitespace-significant syntax
Strengths Web integration, hosting availability Data science, AI/ML, scientific computing
Template Integration Native HTML embedding Separate template engines
Community Large web development community Diverse community across many domains

When to Choose PHP

PHP may be the right choice when:

When to Consider Alternatives

Other technologies might be more suitable when:

Getting Started with PHP

Setting Up a PHP Development Environment

To start developing with PHP, you'll need:

  1. PHP Interpreter: Install PHP on your system
    • Windows: Download from windows.php.net
    • macOS: Use Homebrew: brew install php
    • Linux: Use package manager, e.g., apt install php
  2. Web Server: Apache, Nginx, or PHP's built-in server
    
    # Using PHP's built-in server (for development)
    php -S localhost:8000
                
  3. Database: MySQL, PostgreSQL, or SQLite
  4. All-in-one Packages: Consider using packages like:
    • XAMPP: Windows, macOS, Linux
    • MAMP: macOS, Windows
    • Laragon: Windows (excellent for Laravel development)
  5. Docker: For containerized development
    
    # Example docker-compose.yml for PHP development
    version: '3'
    services:
      web:
        image: php:8.1-apache
        ports:
          - "80:80"
        volumes:
          - ./:/var/www/html
        depends_on:
          - db
      db:
        image: mysql:8.0
        environment:
          MYSQL_ROOT_PASSWORD: root
          MYSQL_DATABASE: myapp
                

Code Editors and IDEs

Popular tools for PHP development include:

First Steps with PHP

  1. Create a simple PHP file:
    
    // index.php
    <!DOCTYPE html>
    <html>
    <head>
        <title>My PHP Page</title>
    </head>
    <body>
        <h1>Welcome to PHP</h1>
        
        <?php
        // Display server information
        echo "<p>PHP Version: " . phpversion() . "</p>";
        echo "<p>Current Time: " . date('Y-m-d H:i:s') . "</p>";
        
        // Create a simple array
        $fruits = ["Apple", "Banana", "Orange"];
        
        // Display the array
        echo "<h2>Fruits:</h2>";
        echo "<ul>";
        foreach ($fruits as $fruit) {
            echo "<li>$fruit</li>";
        }
        echo "</ul>";
        ?>
    </body>
    </html>
                
  2. Run the PHP file:
    • Using PHP's built-in server: php -S localhost:8000
    • Or place it in your web server's document root
  3. Open in browser: Navigate to http://localhost:8000/

Practice Activity: Your First PHP Application

Let's create a simple PHP application that demonstrates basic functionality: a task list manager.

Project Structure


task_manager/
├── index.php       # Main page with task list
├── add_task.php    # Form for adding tasks
├── process.php     # Process form submissions
├── delete.php      # Handle task deletion
├── tasks.json      # Data storage
└── css/
    └── style.css   # Simple styling
        

Step 1: Create the Files

index.php


<!DOCTYPE html>
<html>
<head>
    <title>PHP Task Manager</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <h1>Task Manager</h1>
        
        <a href="add_task.php" class="btn">Add New Task</a>
        
        <h2>Your Tasks</h2>
        
        <?php
        // Load tasks from JSON file
        $tasks = [];
        if (file_exists('tasks.json')) {
            $json_data = file_get_contents('tasks.json');
            $tasks = json_decode($json_data, true) ?: [];
        }
        
        if (empty($tasks)) {
            echo "<p>No tasks yet. Add your first task!</p>";
        } else {
            echo "<ul class='task-list'>";
            foreach ($tasks as $id => $task) {
                $status_class = ($task['completed']) ? 'completed' : '';
                echo "<li class='$status_class'>";
                echo "<span class='task-title'>{$task['title']}</span>";
                echo "<span class='task-date'>Due: {$task['due_date']}</span>";
                echo "<div class='task-actions'>";
                echo "<a href='process.php?action=toggle&id=$id' class='btn-small'>";
                echo ($task['completed']) ? 'Mark Incomplete' : 'Mark Complete';
                echo "</a>";
                echo "<a href='delete.php?id=$id' class='btn-small delete'>Delete</a>";
                echo "</div>";
                echo "</li>";
            }
            echo "</ul>";
        }
        ?>
    </div>
</body>
</html>
        

add_task.php


<!DOCTYPE html>
<html>
<head>
    <title>Add Task - PHP Task Manager</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <h1>Add New Task</h1>
        
        <form action="process.php" method="post">
            <input type="hidden" name="action" value="add">
            
            <div class="form-group">
                <label for="title">Task Title:</label>
                <input type="text" id="title" name="title" required>
            </div>
            
            <div class="form-group">
                <label for="due_date">Due Date:</label>
                <input type="date" id="due_date" name="due_date" required>
            </div>
            
            <div class="form-group">
                <label for="description">Description:</label>
                <textarea id="description" name="description" rows="4"></textarea>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn">Add Task</button>
                <a href="index.php" class="btn">Cancel</a>
            </div>
        </form>
    </div>
</body>
</html>
        

process.php


<?php
// Load existing tasks
$tasks = [];
if (file_exists('tasks.json')) {
    $json_data = file_get_contents('tasks.json');
    $tasks = json_decode($json_data, true) ?: [];
}

// Process actions
$action = $_REQUEST['action'] ?? '';

switch ($action) {
    case 'add':
        // Add new task
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['title'])) {
            $new_task = [
                'title' => htmlspecialchars($_POST['title']),
                'description' => htmlspecialchars($_POST['description'] ?? ''),
                'due_date' => htmlspecialchars($_POST['due_date']),
                'completed' => false,
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            // Generate a unique ID
            $id = uniqid();
            $tasks[$id] = $new_task;
            
            // Save tasks
            file_put_contents('tasks.json', json_encode($tasks, JSON_PRETTY_PRINT));
            
            header('Location: index.php');
            exit;
        }
        break;
        
    case 'toggle':
        // Toggle task completion status
        $id = $_GET['id'] ?? '';
        if (!empty($id) && isset($tasks[$id])) {
            $tasks[$id]['completed'] = !$tasks[$id]['completed'];
            
            // Save tasks
            file_put_contents('tasks.json', json_encode($tasks, JSON_PRETTY_PRINT));
        }
        
        header('Location: index.php');
        exit;
        break;
        
    default:
        // Redirect to home page for invalid actions
        header('Location: index.php');
        exit;
}
?>
        

delete.php


<?php
// Get task ID
$id = $_GET['id'] ?? '';

// Load tasks
$tasks = [];
if (file_exists('tasks.json')) {
    $json_data = file_get_contents('tasks.json');
    $tasks = json_decode($json_data, true) ?: [];
}

// Remove task if it exists
if (!empty($id) && isset($tasks[$id])) {
    unset($tasks[$id]);
    
    // Save updated tasks
    file_put_contents('tasks.json', json_encode($tasks, JSON_PRETTY_PRINT));
}

// Redirect back to task list
header('Location: index.php');
exit;
?>
        

css/style.css


body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
}

.container {
    width: 80%;
    max-width: 800px;
    margin: 2rem auto;
    padding: 2rem;
    background: white;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

h1, h2 {
    color: #333;
}

a {
    text-decoration: none;
}

.btn {
    display: inline-block;
    background: #4CAF50;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    margin-right: 0.5rem;
}

.btn-small {
    padding: 0.25rem 0.5rem;
    font-size: 0.8rem;
}

.delete {
    background: #f44336;
}

.task-list {
    list-style: none;
    padding: 0;
}

.task-list li {
    padding: 1rem;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
}

.task-title {
    font-weight: bold;
    margin-right: 1rem;
}

.task-date {
    color: #666;
    font-size: 0.9rem;
}

.task-actions {
    margin-top: 0.5rem;
}

.completed .task-title {
    text-decoration: line-through;
    color: #888;
}

.form-group {
    margin-bottom: 1rem;
}

label {
    display: block;
    margin-bottom: 0.5rem;
}

input, textarea {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 3px;
}

.form-actions {
    margin-top: 1.5rem;
}
        

Step 2: Set Up the Application

  1. Create the directory structure shown above.
  2. Create each file with the provided code.
  3. Make sure the web server (or PHP's built-in server) has write permissions to the directory to create the tasks.json file.
  4. Start the PHP server: php -S localhost:8000
  5. Open your browser and navigate to http://localhost:8000/

Step 3: Use the Application

  1. Add a few tasks with different due dates.
  2. Mark some tasks as completed.
  3. Delete a task.
  4. Examine the tasks.json file to see how data is stored.

Extension Activities

  1. Add task editing: Create an edit.php page to modify existing tasks.
  2. Implement task categories: Add a category field to tasks and enable filtering by category.
  3. Use a database: Modify the application to use MySQL or SQLite instead of a JSON file.
  4. Add user authentication: Create a simple login system and associate tasks with specific users.

Key Takeaways

Further Resources