Complete PHP Programming Tutorial

Master PHP - the most popular server-side scripting language for web development

Introduction to 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.

Simple PHP Program
<!DOCTYPE html>
<html>
<head>
    <title>PHP Test</title>
</head>
<body>
    <?php echo '<p>Hello World</p>'; ?>
</body>
</html>

Why Learn PHP?

  • Web Development - Powers 78% of all websites with known server-side programming
  • Easy to Learn - Simple syntax compared to many other languages
  • Open Source - Free to use with a large community
  • Database Integration - Excellent support for MySQL and other databases
  • Cross-Platform - Runs on Windows, Linux, macOS
  • Frameworks - Laravel, Symfony, CodeIgniter, etc.

Key Features of PHP

  • Server-side scripting language
  • Can be embedded into HTML
  • Supports many databases
  • Supports object-oriented programming
  • Large standard library
  • Regular updates and improvements

Environment Setup

To start programming in PHP, you need a web server with PHP installed. Here are the common options:

1. Local Development Options

Option Description
XAMPP Apache + MySQL + PHP + Perl (Windows, Linux, macOS)
WAMP Windows Apache MySQL PHP
MAMP Mac Apache MySQL PHP
LAMP Linux Apache MySQL PHP
Docker Containerized PHP environment

2. Installing XAMPP

  1. Download XAMPP from apachefriends.org
  2. Run the installer
  3. Start Apache and MySQL services
  4. Create a file in htdocs folder with .php extension
  5. Access via http://localhost/yourfile.php

3. Online PHP Testing

For quick testing without installation:

Testing PHP Installation
<?php
    phpinfo();
?>

Save this as info.php in your web server's root directory and access it via browser.

Basic Syntax

A PHP script starts with <?php and ends with ?>. PHP statements end with a semicolon (;).

PHP File Structure
<!DOCTYPE html>
<html>
<body>

<?php
    // PHP code goes here
    echo "Hello World!";
?>

</body>
</html>

Key Components

Component Description Example
PHP Tags Delimit PHP code <?php ... ?>
Comments Explanatory notes // Single-line
/* Multi-line */
echo/print Output data echo "Hello";
Variables Store data $name = "John";
Functions Reusable code blocks function greet() { ... }

First PHP Program

<?php
    echo "Welcome to PHP programming!<br>";
    print "This is your first program.";
?>
Welcome to PHP programming!
This is your first program.

Data Types

PHP supports several primitive data types:

Basic Data Types

Data Type Description Example
String Sequence of characters $name = "John";
Integer Whole numbers $age = 25;
Float Decimal numbers $price = 9.99;
Boolean True/False $is_active = true;
Array Collection of values $colors = array("red", "green");
Object Instance of a class $user = new User();
NULL No value $var = NULL;

Checking Data Types

Use var_dump() or gettype() to check variable types:

Type Checking Example
<?php
    $name = "John";
    $age = 25;
    $price = 9.99;
    $is_active = true;

    var_dump($name);    // string(4) "John"
    echo gettype($age);  // integer
?>

Variables

Variables in PHP are declared with a dollar sign $ followed by the variable name.

Variable Declaration

$variable_name = value;
Variable Examples
<?php
    $name = "John Doe";  // String
    $age = 30;          // Integer
    $price = 19.99;     // Float
    $is_admin = true;   // Boolean
    $colors = array("red", "green", "blue"); // Array
?>

Rules for Naming Variables

  • Starts with $ followed by name
  • Name must start with letter or underscore
  • Can contain letters, numbers, underscores
  • Case-sensitive ($name and $Name are different)
  • Cannot start with a number
  • No spaces or special characters

Variable Scope

Scope Description Example
Local Only accessible within function function test() { $x = 5; }
Global Accessible anywhere $x = 5; function test() { global $x; }
Static Persists between function calls function test() { static $x = 0; }

Operators

PHP has various operators for different operations:

Arithmetic Operators

Operator Description Example
+ Addition $x + $y
- Subtraction $x - $y
* Multiplication $x * $y
/ Division $x / $y
% Modulus $x % $y
** Exponentiation $x ** $y

Comparison Operators

Operator Description Example
== Equal $x == $y
=== Identical $x === $y
!= Not equal $x != $y
<> Not equal $x <> $y
!== Not identical $x !== $y
> Greater than $x > $y
< Less than $x < $y

Logical Operators

Operator Description Example
and And $x and $y
or Or $x or $y
xor Xor $x xor $y
&& And $x && $y
|| Or $x || $y
! Not !$x

Operator Example

<?php
    $a = 10;
    $b = 20;

    echo "a + b = " . ($a + $b) . "<br>";
    echo "a < b: " . ($a < $b) . "<br>";
    echo "a == 10 && b == 20: " . ($a == 10 && $b == 20);
?>
a + b = 30
a < b: 1
a == 10 && b == 20: 1

Conditional Statements

Conditional statements are used to perform different actions based on different conditions.

if Statement

if (condition) {
    // code to execute if condition is true
}

if-else Statement

if (condition) {
    // code if true
} else {
    // code if false
}

if-elseif-else Statement

if (condition1) {
    // code if condition1 true
} elseif (condition2) {
    // code if condition2 true
} else {
    // code if all false
}

switch Statement

switch (expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // default code
}
Conditional Example
<?php
    $grade = "B";

    if ($grade == "A") {
        echo "Excellent!";
    } elseif ($grade == "B") {
        echo "Good!";
    } else {
        echo "Keep trying!";
    }

    // Switch example
    $day = "Mon";
    switch ($day) {
        case "Mon":
            echo "Monday";
            break;
        case "Tue":
            echo "Tuesday";
            break;
        default:
            echo "Other day";
    }
?>

Loops

Loops are used to execute the same block of code repeatedly.

while Loop

while (condition) {
    // code to execute
}

do-while Loop

do {
    // code to execute
} while (condition);

for Loop

for (init; condition; increment) {
    // code to execute
}

foreach Loop

foreach ($array as $value) {
    // code to execute
}

// With keys
foreach ($array as $key => $value) {
    // code to execute
}

Loop Examples

<?php
    // while loop
    $i = 1;
    while ($i <= 5) {
        echo $i . " ";
        $i++;
    }

    echo "<br>";

    // for loop
    for ($j = 1; $j <= 5; $j++) {
        if ($j == 3) continue;
        echo $j . " ";
    }

    echo "<br>";

    // foreach loop
    $colors = array("red", "green", "blue");
    foreach ($colors as $color) {
        echo $color . " ";
    }
?>
1 2 3 4 5
1 2 4 5
red green blue

Functions

Functions are blocks of code that perform a specific task and can be reused.

Function Definition

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

Function Call

functionName($arg1, $arg2);
Function Example
<?php
    // Function definition
    function greet($name) {
        return "Hello, $name!";
    }

    // Function call
    echo greet("John");
?>

Default Arguments

function setHeight($minheight = 50) {
    // code
}

Return Type Declarations (PHP 7+)

function addNumbers(float $a, float $b) : float {
    return $a + $b;
}

Variable Functions

<?php
    function sayHello() {
        echo "Hello!";
    }

    $func = "sayHello";
    $func();  // Calls sayHello()
?>

Arrays

Arrays store multiple values in a single variable.

Types of Arrays

  • Indexed arrays - Arrays with numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays

Creating Arrays

// Indexed array
$cars = array("Volvo", "BMW", "Toyota");

// Associative array
$age = array("Peter"=>"35", "Ben"=>"37");

// Short array syntax (PHP 5.4+)
$colors = ["red", "green", "blue"];

Accessing Array Elements

echo $cars[0];      // Volvo
echo $age["Peter"]; // 35
Array Example
<?php
    // Indexed array
    $fruits = ["Apple", "Banana", "Cherry"];
    echo $fruits[1];  // Banana

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

    // Multidimensional array
    $cars = [
        ["Volvo", 22, 18],
        ["BMW", 15, 13]
    ];
    echo $cars[0][0];  // Volvo
?>

Common Array Functions

Function Description Example
count() Count elements count($array)
sort() Sort array sort($array)
array_push() Add element array_push($array, $item)
array_pop() Remove last element array_pop($array)
array_merge() Merge arrays array_merge($arr1, $arr2)

Strings

PHP provides many functions to manipulate strings.

String Creation

$str1 = 'Hello world!';  // Single quotes
$str2 = "Hello world!";  // Double quotes

String Concatenation

$name = "John";
echo "Hello " . $name . "!";  // Hello John!

Common String Functions

Function Description Example
strlen() String length strlen("Hello")
str_word_count() Count words str_word_count($str)
strrev() Reverse string strrev($str)
strpos() Find substring strpos($str, "world")
str_replace() Replace text str_replace("old", "new", $str)
substr() Return part of string substr($str, 0, 5)
trim() Remove whitespace trim($str)
String Example
<?php
    $text = "   Hello World!   ";

    echo strlen($text) . "<br>";          // 17
    echo str_word_count($text) . "<br>";   // 2
    echo strrev($text) . "<br>";          // "   !dlroW olleH   "
    echo strpos($text, "World") . "<br>";  // 9
    echo trim($text) . "<br>";            // "Hello World!"
    echo strtoupper($text) . "<br>";       // "   HELLO WORLD!   "
?>

Forms Handling

PHP can collect form data sent with both GET and POST methods.

GET vs POST

Method Description
GET Data visible in URL, limited length, not secure
POST Data not shown in URL, no size limit, more secure
Simple Form Example
<!-- HTML Form -->
<form method="post" action="welcome.php">
    Name: <input type="text" name="name">
    Email: <input type="text" name="email">
    <input type="submit">
</form>

<?php
    // welcome.php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = $_POST['name'];
        $email = $_POST['email'];

        echo "Welcome $name!<br>";
        echo "Your email is $email";
    }
?>

Form Validation

Always validate form data before processing:

<?php
    $name = $email = "";
    $nameErr = $emailErr = "";

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["name"])) {
            $nameErr = "Name is required";
        } else {
            $name = test_input($_POST["name"]);
        }

        if (empty($_POST["email"])) {
            $emailErr = "Email is required";
        } else {
            $email = test_input($_POST["email"]);
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $emailErr = "Invalid email format";
            }
        }
    }

    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
?>

Cookies & Sessions

Cookies and sessions are used to store information across multiple pages.

Cookies

Small files stored on the user's computer.

// Set cookie
setcookie("user", "John Doe", time() + (86400 * 30), "/");

// Access cookie
echo $_COOKIE["user"];

// Delete cookie
setcookie("user", "", time() - 3600);

Sessions

Store information on the server for a single user session.

// Start session
session_start();

// Set session variables
$_SESSION["username"] = "john123";
$_SESSION["favcolor"] = "blue";

// Access session
echo $_SESSION["username"];

// Destroy session
session_destroy();
Login System Example
<?php
    session_start();

    // Login
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $username = $_POST["username"];
        $password = $_POST["password"];

        // Validate credentials (in real app, check against database)
        if ($username == "admin" && $password == "password") {
            $_SESSION["loggedin"] = true;
            $_SESSION["username"] = $username;
            header("location: welcome.php");
        }
    }

    // Logout
    if (isset($_GET["logout"])) {
        session_destroy();
        header("location: login.php");
    }
?>

File Handling

PHP has several functions for creating, reading, uploading, and editing files.

File Operations

Function Description
fopen() Opens a file
fread() Reads from a file
fwrite() Writes to a file
fclose() Closes a file
file_get_contents() Reads entire file into string
file_put_contents() Writes string to file
File Operations Example
<?php
    // Write to file
    $file = fopen("test.txt", "w");
    fwrite($file, "Hello World!\n");
    fclose($file);

    // Read from file
    $file = fopen("test.txt", "r");
    echo fread($file, filesize("test.txt"));
    fclose($file);

    // Simple way to read
    echo file_get_contents("test.txt");

    // Simple way to write
    file_put_contents("test.txt", "New content");
?>

File Upload

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file: <input type="file" name="fileToUpload">
    <input type="submit" value="Upload" name="submit">
</form>

<?php
    if (isset($_POST["submit"])) {
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "File uploaded successfully";
        } else {
            echo "Error uploading file";
        }
    }
?>

Database (MySQL)

PHP works well with MySQL databases using MySQLi or PDO extensions.

MySQLi (Procedural)

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    // Create table
    $sql = "CREATE TABLE Users (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(30) NOT NULL,
        lastname VARCHAR(30) NOT NULL,
        email VARCHAR(50)
    )";

    if (mysqli_query($conn, $sql)) {
        echo "Table created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

    // Insert data
    $sql = "INSERT INTO Users (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if (mysqli_query($conn, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

    // Select data
    $sql = "SELECT id, firstname, lastname FROM Users";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
        }
    } else {
        echo "0 results";
    }

    mysqli_close($conn);
?>

PDO (Object-Oriented)

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Insert data
        $stmt = $conn->prepare("INSERT INTO Users (firstname, lastname, email)
        VALUES (:firstname, :lastname, :email)");
        $stmt->bindParam(':firstname', $firstname);
        $stmt->bindParam(':lastname', $lastname);
        $stmt->bindParam(':email', $email);

        $firstname = "John";
        $lastname = "Doe";
        $email = "john@example.com";
        $stmt->execute();

        echo "New records created successfully";
    } catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
    $conn = null;
?>

Object-Oriented Programming in PHP

PHP supports object-oriented programming with classes and objects.

Class Definition

class ClassName {
    // Properties
    public $property;
    private $privateProperty;

    // Constructor
    public function __construct($param) {
        $this->property = $param;
    }

    // Methods
    public function method() {
        // code
    }
}

Creating Objects

$object = new ClassName("value");
OOP Example
<?php
    class Car {
        // Properties
        public $brand;
        public $model;
        private $price;

        // Constructor
        public function __construct($brand, $model, $price) {
            $this->brand = $brand;
            $this->model = $model;
            $this->price = $price;
        }

        // Method
        public function getInfo() {
            return "{$this->brand} {$this->model}";
        }

        // Getter
        public function getPrice() {
            return $this->price;
        }
    }

    // Create object
    $myCar = new Car("Toyota", "Corolla", 20000);
    echo $myCar->getInfo();  // Toyota Corolla
    echo $myCar->getPrice(); // 20000
?>

Inheritance

class ChildClass extends ParentClass {
    // Additional properties and methods
}

Interfaces

interface InterfaceName {
    public function method();
}

class ClassName implements InterfaceName {
    public function method() {
        // implementation
    }
}

Error Handling

PHP provides several ways to handle errors and exceptions.

Basic Error Handling

if (!file_exists("file.txt")) {
    die("File not found");
} else {
    $file = fopen("file.txt", "r");
}

Custom Error Handler

function customError($errno, $errstr) {
    echo "<b>Error:</b> [$errno] $errstr";
}

set_error_handler("customError");

echo $undefinedVar; // Triggers custom error

Exceptions

try {
    if ($value > 1) {
        throw new Exception("Value must be 1 or below");
    }
} catch (Exception $e) {
    echo 'Message: ' . $e->getMessage();
}
PDO Exception Handling
<?php
    try {
        $conn = new PDO("mysql:host=localhost;dbname=myDB", "user", "pass");
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $conn->prepare("SELECT * FROM Users WHERE id=?");
        $stmt->execute([$_GET['id']]);
        $user = $stmt->fetch();

        if (!$user) {
            throw new Exception("User not found");
        }
    } catch(PDOException $e) {
        echo "Database Error: " . $e->getMessage();
    } catch(Exception $e) {
        echo "Error: " . $e->getMessage();
    }
?>

Security

PHP applications should implement security best practices.

Common Security Measures

  • Input Validation - Always validate user input
  • Data Sanitization - Clean data before use
  • Prepared Statements - Prevent SQL injection
  • Password Hashing - Use password_hash()
  • CSRF Protection - Use tokens for forms
  • XSS Prevention - Escape output with htmlspecialchars()

Password Hashing

// Hashing a password
$hash = password_hash("mypassword", PASSWORD_DEFAULT);

// Verifying a password
if (password_verify("mypassword", $hash)) {
    // Password correct
}

Preventing SQL Injection

// UNSAFE
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";

// SAFE with prepared statements (MySQLi)
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

// SAFE with PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->execute(['username' => $username, 'password' => $password]);

Preventing XSS

// UNSAFE
echo $_GET['user_input'];

// SAFE
echo htmlspecialchars($_GET['user_input'], ENT_QUOTES, 'UTF-8');

PHP Best Practices

Follow these best practices to write clean, efficient, and maintainable PHP code.

Coding Standards

  • Follow PSR standards (PSR-1, PSR-2, PSR-12)
  • Use meaningful variable and function names
  • Add comments to explain complex logic
  • Limit function size (ideally less than 50 lines)
  • Use proper indentation and formatting

Performance Tips

  • Use opcode caching (OPcache)
  • Minimize database queries
  • Use efficient loops and conditionals
  • Cache frequently accessed data
  • Use PHP's built-in functions when possible

Modern PHP Features

  • Use PHP 8.x features (nullsafe operator, named arguments, etc.)
  • Use type declarations (PHP 7+)
  • Use modern frameworks (Laravel, Symfony)
  • Implement Composer for dependency management
  • Use namespaces to organize code
Modern PHP Example
<?php
declare(strict_types=1);

namespace App\Services;

use App\Exceptions\UserNotFoundException;
use PDO;

class UserService {
    public function __construct(private PDO $db) {}

    public function getUserById(int $id): array {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $user = $stmt->fetch();

        if (!$user) {
            throw new UserNotFoundException("User with ID $id not found");
        }

        return $user;
    }
}

// Usage
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$userService = new UserService($pdo);

try {
    $user = $userService->getUserById(123);
    echo "User: " . htmlspecialchars($user['name']);
} catch (UserNotFoundException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Congratulations!

You've completed the comprehensive PHP programming tutorial. Practice these concepts by building small projects and web applications to reinforce your learning.

Ready to take the next step? Check out our Laravel Framework tutorial to continue your PHP journey.