Reference Guide

Table of Contents

  1. Introduction to PHP & Server-Side Programming

  2. PHP Syntax Basics

  3. Variables, Data Types & Type Juggling

  4. Operators

  5. Control Structures

  6. Functions

  7. Arrays

  8. Strings & String Functions

  9. Forms & User Input (GET & POST)

  10. Input Validation & Sanitization

  11. File I/O

  12. Sessions & Cookies

  13. Object-Oriented PHP

  14. Error Handling

  15. Working with Dates & Times

  16. PHP & the Web: Putting It All Together


1. Introduction to PHP & Server-Side Programming

What is Server-Side Programming?

Web applications use two sides of computing:

Client-Side
Server-Side

Runs in the user's browser

Runs on the web server

HTML, CSS, JavaScript

PHP, Python, Node.js, Ruby

User can see the source code

Source code is hidden from users

Handles UI/UX interactions

Handles logic, data, security

What is PHP?

PHP (PHP: Hypertext Preprocessor) is a widely-used, open-source, server-side scripting language embedded directly into HTML. When a browser requests a .php file, the server executes the PHP code and sends only the resulting HTML back to the client.

Key characteristics:

  • Free and open-source

  • Runs on most web servers (Apache, Nginx) and operating systems

  • Loosely typed (flexible with data types)

  • Enormous ecosystem of frameworks (Laravel, Symfony, WordPress)

  • Powers ~78% of all websites using a known server-side language

The Request-Response Cycle

  1. User visits https://example.com/index.php

  2. Server finds the .php file

  3. PHP engine processes the script

  4. Output (HTML) is sent back to the browser

  5. Browser renders the HTML — the PHP code is never visible

Your First PHP File

A .php file can mix HTML and PHP freely:

Output in browser:


2. PHP Syntax Basics

PHP Tags

PHP code must be enclosed in PHP tags. The standard form is:

The short echo tag (if enabled on the server):

Best Practice: Always use the full <?php tag for maximum compatibility.

Statements and Semicolons

Every PHP statement must end with a semicolon (;). Forgetting this is one of the most common beginner errors.

Comments

echo vs print

Both output text to the browser, but they have subtle differences:

Rule of thumb: Use echo — it's slightly faster and more commonly used.


3. Variables, Data Types & Type Juggling

Variables

PHP variables always start with a dollar sign $:

Variable naming rules:

  • Must start with $ followed by a letter or underscore

  • Can contain letters, numbers, underscores

  • Case-sensitive ($Name and $name are different)

  • Cannot contain spaces or special characters

Data Types

PHP has 8 primitive data types:

Scalar Types

Compound Types

Special Types

Type Juggling (Loose Typing)

PHP automatically converts types based on context — this is called type juggling or type coercion.

Checking & Casting Types

Constants

Constants are like variables but cannot be changed after definition:


4. Operators

Arithmetic Operators

Assignment Operators

Comparison Operators

Important: Always prefer === over == to avoid unexpected type juggling bugs.

Logical Operators

String Operators

Increment/Decrement Operators

Null Coalescing Operator (PHP 7+)

Ternary Operator


5. Control Structures

if / elseif / else

switch

match Expression (PHP 8+)

A cleaner, stricter alternative to switch:

Key difference from switch: match uses strict comparison (===) and does not fall through.

while Loop

do...while Loop

for Loop

foreach Loop

Used specifically for iterating over arrays:

break and continue


6. Functions

Defining and Calling Functions

Parameters & Default Values

Return Values

Type Declarations (PHP 7+)

Variable Scope

Variable Functions & Anonymous Functions

Built-In Functions (Commonly Used)


7. Arrays

Indexed Arrays

Associative Arrays

Multidimensional Arrays

Array Functions


8. Strings & String Functions

String Basics

Common String Functions


9. Forms & User Input (GET & POST)

HTML Forms Review

Accessing GET Data

When a user submits search.php?query=PHP+basics:

Accessing POST Data

GET vs POST Comparison

Feature
GET
POST

Data location

URL query string

Request body

Visibility

Visible in URL

Hidden from URL

Max data size

~2000 chars

Essentially unlimited

Bookmarkable

Yes

No

Browser history

Yes

No

Use cases

Search, filtering, navigation

Login, registration, form submission

Secure?

No

More secure (but still need HTTPS)

PHP Superglobals

PHP provides several built-in global arrays:

Complete Form Example


10. Input Validation & Sanitization

Security Rule #1: Never trust user input. Always validate and sanitize everything.

The Difference

  • Validation — checks if data is in the correct format (is this actually an email address?)

  • Sanitization — cleans data by removing/encoding dangerous characters

htmlspecialchars() — Prevent XSS

Cross-Site Scripting (XSS) is when malicious users inject JavaScript into your page.

filter_var() — Validation & Sanitization

Validation Functions

Regular Expressions in PHP


11. File I/O

Reading Files

Writing Files

File Mode Flags

Mode
Description

'r'

Read only, pointer at beginning

'w'

Write only, truncates file, pointer at beginning

'a'

Write only, pointer at end (append)

'x'

Create and write, fails if file exists

'r+'

Read and write, pointer at beginning

'w+'

Read and write, truncates file

'a+'

Read and write, pointer at end

File System Functions

File Upload Handling


12. Sessions & Cookies

Sessions

Sessions allow you to store data that persists across multiple page loads for a single user. The data is stored on the server and identified by a session ID stored in a cookie.

Session-Based Login System

Cookies

Cookies are stored in the browser. They can persist beyond the browser session.

Feature
Session
Cookie

Storage location

Server

Browser/Client

Security

More secure

Less secure

Capacity

Limited by server

~4KB per cookie

Lifespan

Until browser closes (default)

Can be long-lived

Access

$_SESSION

$_COOKIE

Use for

Sensitive data (login state)

Preferences, tracking


13. Object-Oriented PHP

Classes and Objects

Access Modifiers

Modifier
Class
Subclass
External

public

protected

private

Inheritance

Interfaces and Abstract Classes

Static Properties and Methods

Magic Methods


14. Error Handling

Error Reporting

PHP Error Types

Type
Constant
Description

Fatal

E_ERROR

Script halts (e.g., calling undefined function)

Warning

E_WARNING

Non-fatal, script continues

Notice

E_NOTICE

Minor issue (e.g., undefined variable)

Parse

E_PARSE

Syntax error during compilation

Deprecated

E_DEPRECATED

Using old, removed features

try / catch / finally

Custom Exceptions


15. Working with Dates & Times

The date() Function

Common Date Format Characters

Character
Description
Example

Y

4-digit year

2026

y

2-digit year

26

m

Month (01-12)

02

M

Month abbreviation

Feb

F

Full month name

February

d

Day (01-31)

23

D

Day abbreviation

Mon

l

Full day name

Monday

H

Hour, 24h (00-23)

14

h

Hour, 12h (01-12)

02

i

Minutes (00-59)

30

s

Seconds (00-59)

45

A

AM or PM

PM

U

Unix timestamp

1740322245

Unix Timestamps

DateTime Class (OOP Approach)


16. PHP & the Web: Putting It All Together

A Complete Mini-Application: Grade Calculator

This example demonstrates form handling, validation, sessions, and OOP working together.

index.php

PHP Best Practices Summary

Security

  • Always sanitize output with htmlspecialchars() to prevent XSS

  • Always validate all user input server-side (never trust client-side only)

  • Use prepared statements when working with databases (parameterized queries)

  • Store passwords with password_hash() — never plain text

  • Use HTTPS in production environments

  • Keep session IDs secure; regenerate on login with session_regenerate_id()

Code Quality

  • Use strict type declarations (declare(strict_types=1))

  • Follow PSR coding standards (PSR-1, PSR-2, PSR-12)

  • Separate concerns: keep HTML, PHP logic, and data access in separate layers

  • Use meaningful variable and function names

  • Comment your code, but prefer self-documenting code

Performance

  • Use require_once / include_once to avoid loading files multiple times

  • Avoid queries inside loops

  • Cache expensive operations where possible


Quick Reference Cheat Sheet

Last updated