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).
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
- Server-Side Scripting: PHP code is executed on the server, generating HTML which is then sent to the client.
- Embedded in HTML: PHP can be directly embedded within HTML code, making it easy to mix static and dynamic content.
- Loose Typing: PHP is loosely typed, meaning variables can change types depending on the context.
- Wide Database Support: Built-in support for databases like MySQL, PostgreSQL, SQLite, and more.
- Cross-Platform: Runs on various platforms (Windows, macOS, Linux) and servers (Apache, Nginx, IIS).
- Extensive Ecosystem: Large community, vast libraries, frameworks, and tools.
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
Advantages of PHP
- Low Learning Curve: PHP is relatively easy to learn, especially for beginners in web development.
- Fast Development Cycle: PHP enables rapid development with its simple syntax and immediate execution.
- Huge Community: A vast community provides support, libraries, and resources.
- Widespread Hosting Support: Almost all web hosting providers support PHP, often at lower costs than other technologies.
- Integration with Web Servers: Deep integration with popular web servers like Apache and Nginx.
- Mature Ecosystem: Well-established frameworks (Laravel, Symfony), CMS platforms (WordPress, Drupal), and tools.
Limitations of PHP
- Inconsistent Function Naming: PHP has been criticized for inconsistent naming conventions in its standard library.
- Historical Security Concerns: Earlier versions had security issues, though modern PHP has addressed many of these.
- Performance Limitations: While PHP 7+ made significant improvements, it may still be outperformed by some other languages in certain scenarios.
- Asynchronous Programming: Native support for asynchronous programming is not as mature as in languages like Node.js.
Common Use Cases for PHP
- Content Management Systems: WordPress, Drupal, and Joomla are all built with PHP.
- E-commerce Platforms: Magento, WooCommerce, and PrestaShop are PHP-based.
- Custom Web Applications: From small business websites to enterprise applications.
- RESTful APIs: Modern PHP frameworks excel at building APIs.
- Legacy System Maintenance: Many existing systems use PHP and require ongoing maintenance.
PHP in the Enterprise
Despite its reputation as a language for small projects, PHP powers many large-scale applications and websites:
- Facebook: Originally built with PHP, later developed HHVM and Hack language to enhance PHP performance.
- Wikipedia: Runs on MediaWiki, which is written in PHP.
- Slack: Parts of Slack's backend use PHP.
- Etsy: The e-commerce platform uses PHP extensively.
- WordPress.com: Powers millions of websites with PHP.
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
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:
- Laravel: Currently the most popular PHP framework, known for its elegant syntax and comprehensive feature set, including ORM, routing, middleware, templating, queues, and more.
- Symfony: A set of reusable PHP components and a full-stack framework, focused on enterprise applications. Many other frameworks (including Laravel) use Symfony components.
- CodeIgniter: Known for being lightweight and having minimal configuration, with good performance.
- Slim: A micro-framework focused on building simple yet powerful web applications and APIs.
- Yii: A high-performance framework designed for modern web applications.
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:
- PHP 7+ Performance: PHP 7 and above brought major performance enhancements, with some operations twice as fast as PHP 5.6.
- JIT Compiler: PHP 8 introduced a Just-In-Time compiler for additional performance improvements.
- OPcache: The OPcache extension improves performance by storing precompiled script bytecode in shared memory.
- Caching Solutions: Tools like Redis, Memcached, and APCu provide ways to cache data and reduce database queries.
Deployment Options
PHP applications can be deployed in various ways:
- Traditional Hosting: Shared hosting, VPS, or dedicated servers with Apache or Nginx.
- Containerization: Using Docker to package PHP applications with all dependencies.
- PaaS: Platform-as-a-Service options like Heroku, Platform.sh, or Cloudways.
- Serverless: PHP can now run in serverless environments like AWS Lambda (via custom runtimes), Vercel, or Netlify.
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:
- You need widespread hosting support: PHP is supported by almost all hosting providers.
- Working with CMS platforms: For WordPress, Drupal, or similar CMS-based projects.
- E-commerce requirements: Platforms like Magento, WooCommerce, and PrestaShop.
- Rapid web application development: PHP frameworks like Laravel offer quick development cycles.
- Team familiarity: If your team already knows PHP, leveraging existing expertise.
- Legacy system integration: When working with existing PHP codebases.
When to Consider Alternatives
Other technologies might be more suitable when:
- Building real-time applications: Node.js often excels for WebSockets and real-time features.
- Data science or machine learning: Python has a stronger ecosystem here.
- Microservices architecture: Languages like Go or Node.js might offer advantages.
- Mobile backend needs: Firebase or other specialized BaaS might be more appropriate.
- High-concurrency systems: Languages with better native concurrency support like Go.
Getting Started with PHP
Setting Up a PHP Development Environment
To start developing with PHP, you'll need:
-
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
-
Web Server: Apache, Nginx, or PHP's built-in server
# Using PHP's built-in server (for development) php -S localhost:8000 - Database: MySQL, PostgreSQL, or SQLite
-
All-in-one Packages: Consider using packages like:
- XAMPP: Windows, macOS, Linux
- MAMP: macOS, Windows
- Laragon: Windows (excellent for Laravel development)
-
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:
- PhpStorm: A full-featured IDE with comprehensive PHP support (paid, but free for students)
-
Visual Studio Code: A lightweight editor with excellent PHP extensions
- PHP Intelephense
- PHP Debug
- PHP Intellisense
- Sublime Text: A fast, customizable editor with PHP plugins
- Atom: Open-source editor with PHP packages
First Steps with PHP
-
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> -
Run the PHP file:
- Using PHP's built-in server:
php -S localhost:8000 - Or place it in your web server's document root
- Using PHP's built-in server:
- 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
- Create the directory structure shown above.
- Create each file with the provided code.
-
Make sure the web server (or PHP's built-in server) has write permissions to the directory to create the
tasks.jsonfile. -
Start the PHP server:
php -S localhost:8000 -
Open your browser and navigate to
http://localhost:8000/
Step 3: Use the Application
- Add a few tasks with different due dates.
- Mark some tasks as completed.
- Delete a task.
- Examine the tasks.json file to see how data is stored.
Extension Activities
- Add task editing: Create an edit.php page to modify existing tasks.
- Implement task categories: Add a category field to tasks and enable filtering by category.
- Use a database: Modify the application to use MySQL or SQLite instead of a JSON file.
- Add user authentication: Create a simple login system and associate tasks with specific users.
Key Takeaways
- PHP remains a powerful and widely-used language for web development, powering the majority of dynamic websites.
- Modern PHP (version 7+) offers significant performance improvements and better language features.
- PHP excels in traditional web development, CMS platforms, and e-commerce applications.
- The PHP ecosystem is mature and extensive, with frameworks like Laravel and Symfony offering robust solutions.
- PHP's embedding within HTML makes it intuitive for creating dynamic web pages.
- While it faces competition from newer technologies, PHP continues to evolve and has a strong future in web development.
- Getting started with PHP is relatively easy, with widespread hosting support and extensive documentation.
Further Resources
- PHP Documentation
- PHP The Right Way
- Laracasts (PHP and Laravel tutorials)
- W3Schools PHP Tutorial
- Symfony Documentation
- Laravel Documentation
- Composer Documentation