PHP Programming
PHP (Hypertext Preprocessor) is a widely-used, open-source server-side scripting language designed primarily for web development. This guide covers the core concepts of PHP, from basic syntax to object-oriented programming and database connectivity.
1. Introduction & Environment Setup
PHP code is executed on the server, and the result is returned to the browser as plain HTML.
Setting Up a Local Environment
To run PHP files locally, you need a web server (like Apache or Nginx) and PHP installed. The easiest way to set this up is by using pre-packaged environments:
- XAMPP (Windows, macOS, Linux)
- MAMP (macOS, Windows)
- LocalWP (optimized for WordPress development)
- Docker (for advanced containerized setups)
PHP files use the .php extension. When a user requests a .php file, the server processes the PHP code and sends the generated output to the browser.
2. Basic Syntax & Variables
The PHP Tag
PHP code is written inside <?php and ?> tags. If a file contains only PHP code, it is recommended to omit the closing ?> tag to prevent accidental whitespace issues.
<?php
echo "Hello, World!";
Comments
Comments are ignored by the PHP engine and are used to document code.
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multi-line
comment block
*/
Variables
In PHP, variables start with a dollar sign ($) followed by the variable name.
- Variable names must start with a letter or an underscore.
- They are case-sensitive (
$ageand$Ageare different). - PHP is a loosely typed language; you do not need to explicitly declare the data type.
<?php
$name = "Alex";
$age = 28;
$height = 1.75;
$is_student = true;
// Outputting variables (using double quotes allows variable interpolation)
echo "My name is $name and I am $age years old.";
3. Data Types
PHP supports several data types:
| Data Type | Description | Example |
|---|---|---|
| String | Sequence of characters | "Hello" or 'Hello' |
| Integer | Non-decimal numbers | 42, -7 |
| Float | Decimal numbers | 3.14, 0.005 |
| Boolean | True or False values | true, false |
| Array | Collection of values | array("apple", "banana") |
| Object | Instance of a class | (See OOP section) |
| NULL | Represents no value | null |
4. Operators
Arithmetic Operators
Used to perform standard mathematical calculations.
$sum = 10 + 5; // 15 (Addition)
$difference = 10 - 5; // 5 (Subtraction)
$product = 10 * 5; // 50 (Multiplication)
$quotient = 10 / 5; // 2 (Division)
$remainder = 10 % 3; // 1 (Modulo/Remainder)
Comparison Operators
Used to compare two values. These return a boolean (true or false).
$a = 5;
$b = "5";
$a == $b; // true (Equal value)
$a === $b; // false (Identical: Equal value and same data type)
$a != $b; // false (Not equal value)
$a !== $b; // true (Not identical)
$a > 3; // true (Greater than)
5. Control Structures
Conditionals (If-Else)
Conditional statements execute different blocks of code based on conditions.
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: C or lower";
}
Switch Statement
Used to compare the same variable against multiple values.
<?php
$fav_color = "blue";
switch ($fav_color) {
case "red":
echo "Your favorite color is red.";
break;
case "blue":
echo "Your favorite color is blue.";
break;
default:
echo "Color not recognized.";
}
Loops
Loops run a block of code repeatedly as long as a condition is met.
While Loop
$i = 1;
while ($i <= 5) {
echo "Number: $i <br>";
$i++;
}
For Loop
for ($i = 0; $i < 5; $i++) {
echo "Iteration: $i <br>";
}
6. Functions
Functions are blocks of code that can be repeatedly called.
Declaring and Calling a Function
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("Sarah"); // Outputs: Hello, Sarah!
Strict Typing (Optional but Recommended)
You can declare parameter and return types to make code more reliable.
<?php
declare(strict_types=1);
function addNumbers(int $a, int $b): int {
return $a + $b;
}
echo addNumbers(5, 10); // Outputs: 15
7. Arrays
PHP supports three main types of arrays.
1. Indexed Arrays (Numeric Keys)
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[1]; // Outputs: Banana
// Adding an item
$fruits[] = "Orange";
2. Associative Arrays (Named Keys)
<?php
$user = [
"username" => "johndoe",
"email" => "[email protected]",
"age" => 30
];
echo $user["email"]; // Outputs: [email protected]
3. Iterating Over Arrays
The foreach loop is the most efficient way to loop through arrays.
<?php
$prices = ["Laptop" => 800, "Mouse" => 20, "Keyboard" => 50];
foreach ($prices as $item => $price) {
echo "The $item costs $$price. <br>";
}
8. Working with Forms
PHP uses superglobal variables to collect form data.
-
$_GET: Collects data sent via URL parameters (visible to everyone). -
$_POST: Collects data sent via HTTP POST method (hidden from URL, preferred for forms).
HTML Form (form.html)
<form action="process.php" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<input type="submit" value="Submit">
</form>
PHP Handler (process.php)
When processing input, it is vital to sanitize and validate values to prevent security vulnerabilities.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect and sanitize input
$username = htmlspecialchars($_POST['username']);
if (!empty($username)) {
echo "Welcome, " . $username;
} else {
echo "Username field is empty.";
}
}
9. Object-Oriented Programming (OOP) Basics
OOP is a programming model organized around objects rather than actions.
<?php
class Car {
// Properties (variables inside a class)
public $brand;
public $color;
// Constructor (runs automatically when an object is created)
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
// Method (function inside a class)
public function getDetails() {
return "This car is a " . $this->color . " " . $this->brand . ".";
}
}
// Creating an object (instantiation)
$myCar = new Car("Toyota", "Red");
echo $myCar->getDetails(); // Outputs: This car is a Red Toyota.
10. Database Connection (PDO) & Security
To connect to a database like MySQL, PHP Data Objects (PDO) is recommended because it is secure and supports multiple database drivers.
Connecting to a Database and Running a Safe Query
Always use prepared statements to prevent SQL injection vulnerabilities.
<?php
$host = '127.0.0.1';
$db = 'my_database';
$user = 'root';
$pass = 'your_password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
// Create connection
$pdo = new PDO($dsn, $user, $pass, $options);
// Prepare a secure SQL query
$userId = 1;
$stmt = $pdo->prepare('SELECT username, email FROM users WHERE id = :id');
// Execute with parameters
$stmt->execute(['id' => $userId]);
$user = $stmt->fetch();
if ($user) {
echo "User: " . htmlspecialchars($user['username']) . " (" . htmlspecialchars($user['email']) . ")";
} else {
echo "User not found.";
}
} catch (PDOException $e) {
// In production, log errors instead of echoing them directly
echo "Connection failed: " . $e->getMessage();
}
The guide was created in June 2026.