web-dev4 min read

PHP Tutorial: Learn Server-Side Scripting from Scratch (2026)

PHP Tutorial: Learn Server-Side Scripting from Scratch (2026)

Published:  |  Category: Web Dev  |  Reading time: ~15 min
PHP Tutorial: Learn Server-Side Scripting from Scratch (2026)

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development. Created by Rasmus Lerdorf in 1993, PHP powers over 75% of websites whose server-side language is known, including WordPress, Wikipedia, and Facebook (in its early years). PHP code executes on the server, generating HTML sent to the client.

PHP 8.x introduced JIT compilation, named arguments, attributes, union types, and the match expression — modernizing the language while maintaining backward compatibility. This tutorial covers modern PHP development from syntax fundamentals to security best practices.

PHP Variables and Data Types

PHP variables are loosely typed and prefixed with $. Types include int, float, string, bool, array, object, null, and callable. PHP 8 added union types (int|string) and the mixed type. Arrays are ordered maps functioning as lists or dictionaries.

String interpolation works in double quotes. Constants are defined with define() or const. Type declarations for function parameters and return values are enabled with declare(strict_types=1).

 'Bob', 'email' => 'bob@example.com'];

function formatValue(int|string $value): string {
    return match (true) {
        is_int($value) => "Number: $value",
        is_string($value) => "String: $value",
    };
}

$user = createUser(name: 'Charlie', email: 'charlie@example.com', admin: true);

Control Structures and Functions

PHP supports if, else, elseif, switch, while, for, foreach, and match. The match expression (PHP 8+) returns values and throws UnhandledMatchError for unmatched cases. foreach iterates arrays by value or reference.

Functions support parameters (variadic ...), return types, and arrow functions via fn(). Closures capture variables from parent scope with use. Generators use yield for memory-efficient iteration.

 'OK',
    404 => 'Not Found',
    500 => 'Server Error',
    default => 'Unknown',
};

$numbers = [1, 2, 3, 4, 5];
$squared = array_map(fn($n) => $n * $n, $numbers);

function paginate(int $total, int $perPage = 10): Generator {
    for ($i = 0; $i < $total; $i += $perPage) {
        yield ['offset' => $i, 'limit' => $perPage];
    }
}

Form Handling and Superglobals

PHP superglobals provide access to external data: $_GET for query params, $_POST for form data, $_REQUEST for combined GET/POST, $_FILES for file uploads, $_SERVER for metadata, $_COOKIE for cookies. Always validate and sanitize user input.

File uploads are handled through $_FILES with name, type, tmp_name, error, and size. Validate file type and size, use move_uploaded_file() to store, and implement CSRF protection with tokens.


Database Access with PDO

PDO (PHP Data Objects) is PHP's database abstraction layer supporting MySQL, PostgreSQL, SQLite with a unified API. Prepared statements with parameterized queries prevent SQL injection — the database engine separates query structure from data values.

Transactions use beginTransaction(), commit(), rollback(). Fetch modes: FETCH_ASSOC (column names), FETCH_OBJ (objects), FETCH_CLASS (typed classes). Set error mode to ERRMODE_EXCEPTION for robust handling.

 PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
]);

$stmt = $pdo->prepare(
    'INSERT INTO posts (title, body, author_id) VALUES (:title, :body, :author_id)'
);
$stmt->execute([
    'title' => 'PHP Tutorial',
    'body' => 'Learning PDO...',
    'author_id' => 1,
]);

$stmt = $pdo->prepare('SELECT * FROM posts WHERE id = ?');
$stmt->execute([$postId]);
$post = $stmt->fetch();

Classes and Object-Oriented PHP

PHP supports classes, inheritance, interfaces, traits, and abstract classes. Visibility modifiers: public, protected, private. Constructor property promotion (PHP 8+) reduces boilerplate. PHP 8.1 introduced enums and readonly properties.

Traits enable horizontal code reuse. Interfaces define contracts. Enums (PHP 8.1+) provide type-safe constant sets. The __invoke() method makes objects callable as functions.

status = PostStatus::Published;
    }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'status' => $this->status->value,
        ];
    }
}

$post = new Post(1, 'PHP 8 Features', PostStatus::Draft);
$post->publish();
echo json_encode($post->toArray());

Sessions, Cookies, and Security

PHP sessions store user data between requests. Call session_start() at the start of every page, then use $_SESSION. Session data is stored in files or databases for multi-server setups. Configure lifetime and cookie parameters in php.ini.

Security: use HTTPS, set session.cookie_secure and session.cookie_httponly, regenerate session IDs after login, hash passwords with password_hash() using BCRYPT, validate input with filter functions, escape output with htmlspecialchars().

 1800)) {
    session_unset();
    session_destroy();
    header('Location: /login.php');
    exit;
}

$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$verified = password_verify($inputPassword, $hash);

Frequently Asked Questions

Is PHP still relevant for modern web development?

Yes. PHP powers 75%+ of websites. PHP 8.x brought JIT compilation, making it competitive with Node.js and Python. The ecosystem of Composer, Laravel, and Symfony remains mature.

What is the difference between echo and print?

echo is marginally faster, takes multiple arguments, and has no return value. print always returns 1, takes one argument. echo is preferred.

How do I prevent SQL injection in PHP?

Always use prepared statements with PDO. Never concatenate user input into query strings. Validate input types — cast integers with (int).

What is Composer?

Composer is PHP's dependency manager (like npm for Node.js). It handles autoloading, version management, and dependency resolution via composer.json.

Originally published on Ayodhyyya. Last updated June 1, 2026.