PHP Programming Guide
Master PHP, a powerful server-side scripting language for dynamic web development.
Try PHP OnlineIntroduction to PHP
PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development. It is embedded in HTML and used to create dynamic web content.
<?php
// Basic Hello World example
echo "Hello, World!";
// Embedding PHP in HTML
$name = "Guest";
?>
<p>Welcome, <?php echo htmlspecialchars($name); ?>!</p>
PHP Basics
Variables and Naming
Variables store data, start with $, and are case-sensitive. Rules: start with a letter or underscore, no numbers at start, use meaningful names.
<?php
// Variable declarations
$name = "John"; // String
$age = 30; // Integer
$price = 19.99; // Float
$isActive = true; // Boolean
$_count = 100; // Valid variable name
// Naming conventions
$userName = "Alice"; // CamelCase
$first_name = "Bob"; // snake_case
// Type casting
$number = (int)"42"; // String to integer
$string = (string)123; // Integer to string
// Variable variables
$varName = "message";
$$varName = "Dynamic variable";
echo $message; // Outputs: Dynamic variable
// Invalid examples: $1name, $#name
echo "Name: " . htmlspecialchars($name) . ", Age: $age";
?>
Data Types
PHP supports 8 primitive types with dynamic typing.
- String: Text data
- Integer: Whole numbers
- Float: Decimal numbers
- Boolean: true/false
- Array: Ordered collections
- Object: Instances of classes
- NULL: No value
- Resource: Special handles (e.g., DB connections)
<?php
$str = "Hello"; // String
$int = 42; // Integer
$float = 3.14; // Float
$bool = true; // Boolean
$arr = [1, 2, 3]; // Array
$null = NULL; // NULL
class User {
public string $name = "Guest";
}
$obj = new User(); // Object
$resource = fopen("test.txt", "r"); // Resource
// Type checking
var_dump(is_string($str)); // bool(true)
var_dump(gettype($int)); // string "integer"
echo $obj->name; // Guest
?>
Constants
Defining Constants
Constants are immutable values defined using define()
or const
. They are case-sensitive by default.
<?php
// Using define
define("SITE_NAME", "MyWebsite");
define("DEBUG_MODE", true, true); // Case-insensitive
echo SITE_NAME;
// Using const
const MAX_USERS = 100;
echo MAX_USERS;
// Class constant
class Config {
const VERSION = "1.0";
public function getVersion(): string {
return self::VERSION;
}
}
echo Config::VERSION;
// Magic constants
echo __FILE__; // Current file path
echo __LINE__; // Current line number
?>
Input and Output
Output
Use echo
, print
, print_r
, or var_dump
for output.
<?php
// Basic output
echo "Simple output\n";
print "Print works too\n";
// Formatted output
printf("Price: %.2f\n", 19.99);
sprintf("User: %s, Age: %d", "John", 30);
// Debugging output
print_r(["array" => [1, 2, 3]]);
var_dump("Debug info");
// JSON output
echo json_encode(["name" => "Alice", "age" => 25]);
?>
Input
Handle user input securely via forms or CLI.
<?php
// Form input with sanitization
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING) ?? '';
echo "Hello, " . htmlspecialchars($name);
// Command-line input
echo "Enter your name: ";
$name = trim(fgets(STDIN));
echo "Welcome, " . htmlspecialchars($name);
// File input handling
if (isset($_FILES['file'])) {
$file_name = filter_var($_FILES['file']['name'], FILTER_SANITIZE_STRING);
echo "Uploaded file: " . htmlspecialchars($file_name);
}
?>
Operators
Arithmetic
Perform mathematical operations.
<?php
$a = 10;
$b = 5;
echo $a + $b; // 15
echo $a - $b; // 5
echo $a * $b; // 50
echo $a / $b; // 2
echo $a % $b; // 0
echo $a ** $b; // 100000
// Increment/Decrement
$a++;
echo $a; // 11
$b--;
echo $b; // 4
?>
Comparison
Compare values for equality or order.
<?php
$a = 10;
$b = "10";
var_dump($a == $b); // true
var_dump($a === $b); // false
var_dump($a != $b); // false
var_dump($a !== $b); // true
var_dump($a > $b); // false
var_dump($a <=> $b); // 0
// Null coalescing operator
$name = $_GET['name'] ?? 'Guest';
echo $name;
?>
Logical and Assignment
Combine conditions and assign values.
<?php
$a = true;
$b = false;
var_dump($a && $b); // false
var_dump($a || $b); // true
var_dump(!$a); // false
// Assignment
$x = 10;
$x += 5; // $x = 15
$x ??= 20; // Assign if null
$x *= 2; // $x = 30
echo $x;
// Short-circuit evaluation
$result = $a ?: 'Default';
echo $result;
?>
Control Structures
If-Else
Conditional execution of code.
<?php
$age = 18;
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teenager";
} else {
echo "Child";
}
// Ternary operator
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
// Match expression (PHP 8.0+)
$role = match ($age) {
18 => "Adult",
13 => "Teenager",
default => "Child"
};
echo $role;
?>
Loops
Repeat code execution.
<?php
// For loop
for ($i = 0; $i < 5; $i++) {
echo "$i ";
}
// While loop
$j = 0;
while ($j < 3) {
echo "$j ";
$j++;
}
// Do-while
$k = 0;
do {
echo "$k ";
$k++;
} while ($k < 3);
// Foreach with key-value
$colors = ["red" => "#FF0000", "green" => "#00FF00", "blue" => "#0000FF"];
foreach ($colors as $name => $hex) {
echo "$name: $hex ";
}
// Break and continue
for ($i = 0; $i < 10; $i++) {
if ($i % 2 === 0) continue;
if ($i > 5) break;
echo $i;
}
?>
Switch
Multi-way branching.
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of week";
break;
case "Friday":
echo "Weekend coming!";
break;
default:
echo "Midweek";
}
// Switch with multiple cases
$code = 404;
switch ($code) {
case 200, 201:
echo "Success";
break;
case 404:
echo "Not Found";
break;
default:
echo "Error";
}
?>
Functions & Arrays
Functions
Reusable code blocks with optional parameters.
<?php
// Basic function with type hints
function greet(string $name): string {
return "Hello, $name!";
}
echo greet("Alice");
// Default parameters
function sayHi(string $name = "Guest"): string {
return "Hi, $name";
}
echo sayHi();
// Arrow function (PHP 7.4+)
$add = fn(int $a, int $b): int => $a + $b;
echo $add(5, 3);
// Variadic parameters
function sum(...$numbers): int {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4);
// Anonymous function
$multiply = function(int $a, int $b): int {
return $a * $b;
};
echo $multiply(4, 5);
// Closure with use
$factor = 2;
$scale = function(int $x) use ($factor): int {
return $x * $factor;
};
echo $scale(10);
?>
Arrays
Store multiple values in a single variable.
<?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
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][1]; // 5
// Array functions
$nums = [1, 2, 3];
array_push($nums, 4);
echo count($nums); // 4
$double = array_map(fn($n) => $n * 2, $nums); // [2, 4, 6, 8]
echo implode(", ", $double);
// Array destructuring (PHP 7.1+)
[$a, $b, $c] = $fruits;
echo "$a, $b, $c";
// Array filtering
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
print_r($evens);
?>
Object-Oriented Programming
Classes and Objects
Define reusable classes with properties and methods.
<?php
class User {
private string $name;
private int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function getName(): string {
return $this->name;
}
public function setAge(int $age): void {
if ($age < 0) {
throw new InvalidArgumentException("Age cannot be negative");
}
$this->age = $age;
}
}
$user = new User("Alice", 25);
echo $user->getName(); // Alice
$user->setAge(30);
?>
Inheritance and Interfaces
Extend classes and implement interfaces for polymorphism.
<?php
interface Logger {
public function log(string $message): void;
}
class User extends Person implements Logger {
private string $email;
public function __construct(string $name, int $age, string $email) {
parent::__construct($name, $age);
$this->email = $email;
}
public function log(string $message): void {
echo "Logging: $message";
}
}
class Person {
protected string $name;
protected int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
}
$user = new User("Bob", 30, "bob@example.com");
$user->log("User created");
?>
Regular Expressions
Using Regex in PHP
Validate and manipulate strings with regular expressions.
<?php
// Email validation
$email = "test@example.com";
if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
echo "Valid email";
} else {
echo "Invalid email";
}
// String replacement
$text = "Hello, World!";
$new_text = preg_replace("/World/", "PHP", $text);
echo $new_text; // Hello, PHP!
// Extract matches
$phone = "Phone: 123-456-7890";
preg_match("/\d{3}-\d{3}-\d{4}/", $phone, $matches);
print_r($matches);
?>
Error Handling
Try-Catch and Exceptions
Handle errors gracefully using try-catch blocks.
<?php
try {
$number = 0;
if ($number === 0) {
throw new Exception("Division by zero");
}
echo 10 / $number;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "\nOperation completed.";
}
// Custom exception
class CustomException extends Exception {}
try {
throw new CustomException("Custom error");
} catch (CustomException $e) {
echo $e->getMessage();
}
// Error handling with set_error_handler
set_error_handler(function($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
});
echo $undefined; // Triggers ErrorException
?>
Form Handling & Superglobals
Form Handling
Securely process form data with validation.
PHP Processing (welcome.php):
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['submit'])) {
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
if ($name && filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Welcome " . htmlspecialchars($name) . "! Your email is " . htmlspecialchars($email) . ".";
} else {
echo "Invalid input. Please provide a valid name and email.";
}
}
?>
Superglobals
Global variables accessible anywhere.
$_GET
: URL parameters$_POST
: Form data$_SESSION
: Session data$_COOKIE
: Browser cookies$_SERVER
: Server information$_REQUEST
: GET, POST, and COOKIE data
<?php
// Secure session handling
session_start([
'cookie_httponly' => true,
'use_strict_mode' => true
]);
$_SESSION['username'] = 'admin';
// Secure cookie
setcookie("user", "John", [
"expires" => time() + 3600,
"httponly" => true,
"secure" => true
]);
// Accessing superglobals
echo htmlspecialchars($_SERVER['HTTP_HOST']);
echo isset($_GET['id']) ? htmlspecialchars($_GET['id']) : 'No ID provided';
?>
Database Connection
MySQLi Connection
Connect to MySQL database securely with prepared statements.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
throw new Exception("Connection failed: " . $conn->connect_error);
}
// Prepared statement
$stmt = $conn->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . htmlspecialchars($row["name"]) . "<br>";
}
} else {
echo "No results";
}
$stmt->close();
} catch (Exception $e) {
error_log($e->getMessage());
echo "An error occurred. Please try again later.";
} finally {
$conn->close();
}
?>
PDO Connection
Use PDO for database abstraction and security.
<?php
$dsn = "mysql:host=localhost;dbname=myDB;charset=utf8mb4";
$username = "username";
$password = "password";
try {
$pdo = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
while ($row = $stmt->fetch()) {
echo "ID: " . $row["id"] . " - Name: " . htmlspecialchars($row["name"]) . "<br>";
}
} catch (PDOException $e) {
error_log($e->getMessage());
echo "Database error: Please try again later.";
}
?>
File Handling
Reading Files
Read files safely with error handling.
<?php
try {
$content = file_get_contents("test.txt");
if ($content === false) {
throw new Exception("Cannot read file");
}
echo htmlspecialchars($content);
$file = fopen("test.txt", "r");
if ($file === false) {
throw new Exception("Cannot open file");
}
while (!feof($file)) {
echo htmlspecialchars(fgets($file)) . "<br>";
}
fclose($file);
} catch (Exception $e) {
echo "Error reading file: " . htmlspecialchars($e->getMessage());
}
// Read CSV file
$csv = array_map('str_getcsv', file('data.csv'));
print_r($csv);
?>
Writing Files
Write to files with error handling.
<?php
try {
if (file_put_contents("test.txt", "Hello World!") === false) {
throw new Exception("Cannot write to file");
}
$file = fopen("test.txt", "a");
if ($file === false) {
throw new Exception("Cannot open file");
}
fwrite($file, "\nNew line");
fclose($file);
// Write JSON to file
$data = ["name" => "John", "age" => 30];
file_put_contents("data.json", json_encode($data, JSON_PRETTY_PRINT));
} catch (Exception $e) {
echo "Error writing file: " . htmlspecialchars($e->getMessage());
}
?>
Security Best Practices
Securing PHP Applications
Implement security measures to protect against common vulnerabilities.
- Use
strict_types=1
for type safety. - Sanitize and validate all user inputs.
- Use prepared statements for database queries.
- Enable secure session settings.
- Protect against XSS with
htmlspecialchars()
. - Prevent SQL injection with PDO or MySQLi.
- Use secure password hashing (
password_hash()
). - Implement CSRF protection for forms.
<?php
// Secure form handling
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
if (!$name) {
throw new InvalidArgumentException("Invalid name");
}
// Password hashing
$password = "secure123";
$hash = password_hash($password, PASSWORD_BCRYPT);
if (password_verify($password, $hash)) {
echo "Password is valid";
}
// CSRF protection
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;
?>
<form method="post">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
<input type="text" name="input" class="bg-gray-700 text-gray-100 border-gray-600">
<input type="submit" class="bg-blue-700 text-white py-2 px-4 rounded-lg hover:bg-blue-600">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
echo "Valid CSRF token";
} else {
echo "Invalid CSRF token";
}
}
?>