PHP

PHP is one of the most popular server-side programming languages, powering millions of websites including Facebook, WordPress, and Wikipedia. This comprehensive guide will help you learn PHP from scratch and build dynamic web applications.

Why Learn PHP?

PHP has been a cornerstone of web development for decades. Here’s why it remains a top choice:

  • Easy to Learn: PHP syntax is simple and intuitive for beginners
  • Web-Focused: Built specifically for web development
  • Large Community: Millions of developers and extensive documentation
  • Cost-Effective: Free and open-source with affordable hosting
  • Fast Development: Rapid prototyping and deployment
  • Framework Ecosystem: Laravel, Symfony, and many more powerful frameworks

Getting Started with PHP

Installation

Get PHP installed on your system with our detailed installation guides:

PHP installation is straightforward and works on all operating systems. Our guides cover web server setup (Apache/Nginx), database integration (MySQL/MariaDB), and development environment configuration.

Your First PHP Program

Create a file called hello.php:

<?php
echo "Hello, World!";
?>

If you’re using a web server, place this file in your web root and access it through your browser. Or run it from command line:

php hello.php

Output: Hello, World!

Congratulations! You’ve written your first PHP program.

PHP Basics

Variables and Data Types

Variables store information that your program can use:

<?php
// Numbers
$age = 25;
$price = 19.99;
$temperature = -5;

// Text (strings)
$name = "Alice";
$message = 'Welcome to PHP!';

// Boolean values
$is_student = true;
$has_permission = false;

// Arrays
$fruits = ["apple", "banana", "orange"];
$person = [
    "name" => "Bob",
    "age" => 30,
    "city" => "New York"
];

// Null
$result = null;

// Display variables
echo "Name: $name<br>";
echo "Age: $age<br>";
echo "Is student: " . ($is_student ? 'Yes' : 'No') . "<br>";
?>

Basic Operations

<?php
// Math operations
$x = 10;
$y = 3;

echo $x + $y . "<br>";    // Addition: 13
echo $x - $y . "<br>";    // Subtraction: 7
echo $x * $y . "<br>";    // Multiplication: 30
echo $x / $y . "<br>";    // Division: 3.333...
echo $x % $y . "<br>";    // Modulus (remainder): 1
echo $x ** $y . "<br>";   // Exponent: 1000

// String operations
$first_name = "John";
$last_name = "Doe";
$full_name = $first_name . " " . $last_name;
echo $full_name . "<br>";  // Output: John Doe

// String functions
$text = "hello world";
echo strlen($text) . "<br>";           // 11
echo strtoupper($text) . "<br>";       // HELLO WORLD
echo ucwords($text) . "<br>";          // Hello World
?>

Arrays

Arrays store multiple values:

<?php
// Indexed arrays
$fruits = ["apple", "banana", "orange"];
$numbers = [1, 2, 3, 4, 5];

// Accessing items
echo $fruits[0] . "<br>";    // apple
echo $fruits[2] . "<br>";    // orange

// Array operations
$fruits[] = "grape";         // Add to end
array_push($fruits, "kiwi"); // Add multiple
unset($fruits[1]);           // Remove item

echo count($fruits) . "<br>";  // Number of items
echo in_array("apple", $fruits) ? "Found" : "Not found" . "<br>";

// Associative arrays
$person = [
    "name" => "Alice",
    "age" => 30,
    "email" => "[email protected]"
];

// Accessing values
echo $person["name"] . "<br>";      // Alice
echo $person["age"] . "<br>";       // 30

// Adding and updating
$person["city"] = "New York";      // Add new key
$person["age"] = 31;               // Update existing key

// Multidimensional arrays
$students = [
    [
        "name" => "John",
        "grades" => [85, 92, 78]
    ],
    [
        "name" => "Jane",
        "grades" => [90, 88, 95]
    ]
];

echo $students[0]["name"] . "<br>";        // John
echo $students[1]["grades"][0] . "<br>";  // 90
?>

Control Flow

If Statements

Make decisions in your code:

<?php
$age = 20;

if ($age < 18) {
    echo "You're a minor";
} elseif ($age >= 18 && $age < 65) {
    echo "You're an adult";
} else {
    echo "You're a senior";
}

// Ternary operator
$message = ($age >= 18) ? "You can vote" : "You cannot vote";
echo "<br>" . $message;

// Null coalescing operator (PHP 7+)
$username = $_GET['username'] ?? "Guest";
echo "<br>Welcome, " . $username;
?>

Loops

Repeat actions multiple times:

<?php
// For loop
for ($i = 0; $i < 5; $i++) {
    echo "Count: $i<br>";
}

// Foreach loop with indexed array
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
    echo "I like $fruit<br>";
}

// Foreach loop with associative array
$person = [
    "name" => "Alice",
    "age" => 30,
    "city" => "New York"
];

foreach ($person as $key => $value) {
    echo "$key: $value<br>";
}

// While loop
$count = 0;
while ($count < 5) {
    echo "While count: $count<br>";
    $count++;
}

// Do-while loop
do {
    echo "Do-while count: $count<br>";
    $count--;
} while ($count > 0);
?>

Functions

Functions are reusable blocks of code:

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

// Function with default parameter
function greetWithTitle($name, $title = "Mr./Ms.") {
    return "Hello, $title $name!";
}

// Function with multiple parameters
function calculateArea($length, $width) {
    return $length * $width;
}

// Function that returns multiple values
function getPersonInfo() {
    $name = "John Doe";
    $age = 30;
    $city = "New York";
    return compact('name', 'age', 'city');
}

// Using functions
echo greet("Bob") . "<br>";
echo greetWithTitle("Alice") . "<br>";
echo greetWithTitle("Charlie", "Dr.") . "<br>";

$area = calculateArea(10, 5);
echo "Area: $area<br>";

$info = getPersonInfo();
echo "Name: {$info['name']}, Age: {$info['age']}<br>";

// Variable functions
function add($a, $b) {
    return $a + $b;
}

function subtract($a, $b) {
    return $a - $b;
}

$operation = "add";
echo $operation(5, 3) . "<br>"; // 8

$operation = "subtract";
echo $operation(5, 3) . "<br>"; // 2
?>

Working with Forms

Handle user input from HTML forms:

<?php
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get form data with sanitization
    $name = htmlspecialchars($_POST['name'] ?? '');
    $email = htmlspecialchars($_POST['email'] ?? '');
    $message = htmlspecialchars($_POST['message'] ?? '');
    
    // Validate required fields
    $errors = [];
    
    if (empty($name)) {
        $errors[] = "Name is required";
    }
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Valid email is required";
    }
    
    if (empty($message)) {
        $errors[] = "Message is required";
    }
    
    // Process if no errors
    if (empty($errors)) {
        // Save to database or send email
        echo "Thank you, $name! Your message has been received.";
    } else {
        echo "Please fix the following errors:<br>";
        foreach ($errors as $error) {
            echo "- $error<br>";
        }
    }
}
?>

<!-- HTML Form -->
<form method="POST" action="">
    <div>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
    </div>
    <br>
    <div>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
    </div>
    <br>
    <div>
        <label for="message">Message:</label><br>
        <textarea id="message" name="message" rows="4" cols="50" required></textarea>
    </div>
    <br>
    <button type="submit">Send Message</button>
</form>

Database Connectivity

Connect to MySQL database:

<?php
// Database configuration
$host = 'localhost';
$dbname = 'myapp';
$username = 'root';
$password = '';

try {
    // Create PDO connection
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    
    // Set error mode
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Insert data
    $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->execute(['John Doe', '[email protected]']);
    
    // Select data
    $stmt = $pdo->query("SELECT * FROM users");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "Name: " . $row['name'] . ", Email: " . $row['email'] . "<br>";
    }
    
} catch (PDOException $e) {
    echo "Database error: " . $e->getMessage();
}
?>

PHP Topics

Popular PHP Frameworks

Web Development

  • Laravel: Modern, feature-rich framework with elegant syntax
  • Symfony: Robust, enterprise-level framework
  • CodeIgniter: Lightweight, fast framework for small projects

CMS Platforms

  • WordPress: Most popular content management system
  • Drupal: Enterprise CMS with powerful features
  • Joomla: Flexible CMS for various websites

Micro Frameworks

  • Slim: Minimalist framework for APIs
  • Lumen: Lightning-fast micro-framework by Laravel
  • Fat-Free: Lightweight, easy-to-learn framework

Next Steps

After mastering these basics, you can explore:

  1. Object-Oriented Programming: Classes, objects, inheritance
  2. Modern PHP: PHP 8+ features and type declarations
  3. Framework Development: Build apps with Laravel or Symfony
  4. API Development: RESTful APIs and microservices
  5. Testing: Unit testing with PHPUnit
  6. Composer: Package management and dependency handling

Learning Resources

Official Documentation

Interactive Learning

Practice Platforms

Common PHP Patterns

Autoloading Classes

<?php
// Composer autoloader
require 'vendor/autoload.php';

// Custom autoloader
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$user = new User(); // Automatically loads User.php
?>

Singleton Pattern

<?php
class Database {
    private static $instance = null;
    private $connection;
    
    private function __construct() {
        $this->connection = new PDO('mysql:host=localhost', 'user', 'pass');
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __clone() {}
    private function __wakeup() {}
}

$db = Database::getInstance();
?>

Tips for PHP Success

  1. Use Composer: Modern PHP development requires package management
  2. Follow PSR Standards: Use PSR-1, PSR-2, PSR-4 for code quality
  3. Enable Error Reporting: Develop with error_reporting(E_ALL)
  4. Use Prepared Statements: Prevent SQL injection
  5. Stay Updated: PHP 7+ offers significant improvements
  6. Join Communities: PHP forums, Stack Overflow, and conferences

Summary

PHP remains a powerful choice for web development because it offers:

  • Easy learning curve for beginners
  • Massive ecosystem of frameworks and tools
  • Excellent documentation and community support
  • Cost-effective hosting solutions
  • Rapid development capabilities
  • Strong job market demand

Start with the fundamentals shown here, practice building real applications, and gradually explore modern PHP features and frameworks. The key is consistent practice and building projects that solve real problems.


External Resources:

Related Tutorials:

Last updated on