PHP Programming
I have been programming in PHP since 2004 when I needed to create a privacy policy module for PHP-Nuke. While I've never been a professional PHP developer, I have enjoyed making websites and tools with it over the years. Despite what some JavaScript developers will have you believe, PHP is not dying, and it is much better than it was in the early 2000s.
This section will cover some basics of PHP programming and also include some notes and code snippets.
What You Need
- PHP 8.1+ installed locally (8.2 or 8.3 is even better)
- A text editor
- Terminal access
Quick local test:
php -v
If you see a version number, you are ready.
Hello World
Create hello.php:
<?php echo "Hello, World!";
What this does: Prints text to the terminal or browser.
Run it:
php hello.php
Expected output:
Hello, World!
Variables and Basic Types
<?php $name = "Travis"; $age = 30; $isAdmin = false; $height = 5.11; echo "Name: $name\n"; echo "Age: $age\n"; echo "Height: $height\n"; echo "Admin: " . ($isAdmin ? "yes" : "no") . "\n";
What this does: Stores text, numbers, and booleans in variables and prints them.
Expected output:
Name: Travis Age: 30 Height: 5.11 Admin: no
If / Else Conditionals
<?php
$score = 87;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: Needs work";
}
What this does: Runs one branch based on conditions.
Expected output:
Grade: B
Switch Case
<?php
$status = "pending";
switch ($status) {
case "new":
echo "Order created";
break;
case "pending":
echo "Waiting for payment";
break;
case "shipped":
echo "On the way";
break;
default:
echo "Unknown status";
}
What this does: Picks one action from multiple exact values.
Expected output:
Waiting for payment
Loops: for, while, and foreach
<?php
for ($i = 1; $i <= 3; $i++) {
echo "for: $i\n";
}
$n = 1;
while ($n <= 2) {
echo "while: $n\n";
$n++;
}
$langs = ["PHP", "Python", "Bash"];
foreach ($langs as $lang) {
echo "foreach: $lang\n";
}
What this does: Repeats actions with three common loop styles.
Expected output:
for: 1 for: 2 for: 3 while: 1 while: 2 foreach: PHP foreach: Python foreach: Bash
Arrays
<?php
$user = [
"name" => "NightFox",
"site" => "nightfox818.com",
"topics" => ["PHP", "Linux", "Networking"]
];
echo $user["name"] . " runs " . $user["site"] . "\n";
echo "First topic: " . $user["topics"][0];
What this does: Uses associative arrays and nested arrays.
Expected output:
NightFox runs nightfox818.com First topic: PHP
Functions
<?php
function greet(string $name): string
{
return "Hello, " . $name . "!";
}
echo greet("World");
What this does: Defines reusable logic and returns a value.
Expected output:
Hello, World!
Match Expression (PHP 8+)
<?php
$httpCode = 404;
$message = match ($httpCode) {
200 => "OK",
404 => "Not Found",
500 => "Server Error",
default => "Unknown"
};
echo $message;
What this does: Maps input values to output values more cleanly than many chained ifs.
Expected output:
Not Found
Try / Catch Error Handling
<?php
try {
if (!file_exists("config.php")) {
throw new Exception("config.php is missing");
}
echo "Config loaded";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
What this does: Handles exceptions without crashing the whole script.
Expected output (if file is missing):
Error: config.php is missing
Working with Forms
Forms are core PHP workflow. Use POST, validate input, and escape output.
<?php
$name = '';
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
if ($name === '') {
$message = 'Please enter your name.';
} else {
$safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
$message = "Welcome, $safeName.";
}
}
?>
<form method="post">
<label for="name">Name:</label>
<input id="name" name="name" type="text">
<button type="submit">Submit</button>
</form>
<p><?= $message ?></p>
What this does: Accepts user input, validates it, and safely displays it.
Expected output behavior:
Empty submit: Please enter your name. Submit "Alex": Welcome, Alex.
Database Access with PDO
Use PDO + prepared statements by default.
<?php
$pdo = new PDO(
'mysql:host=localhost;dbname=myapp;charset=utf8mb4',
'dbuser',
'dbpass',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]
);
$stmt = $pdo->prepare('SELECT id, username FROM users WHERE email = :email');
$stmt->execute(['email' => '[email protected]']);
$user = $stmt->fetch();
if ($user) {
echo "User ID: " . $user['id'];
} else {
echo "User not found";
}
What this does: Connects to MySQL safely and queries using a bound parameter.
Expected output behavior:
Matching row: User ID: 123 No row: User not found
Sessions (Login State)
<?php
session_start();
if (!isset($_SESSION['views'])) {
$_SESSION['views'] = 0;
}
$_SESSION['views']++;
echo "Views this session: " . $_SESSION['views'];
What this does: Persists data across requests for the same visitor.
Expected output behavior:
First refresh: Views this session: 1 Second refresh: Views this session: 2
Useful Built-In Functions
| Function | What it does | Example |
|---|---|---|
strlen() |
Gets string length | strlen("php") returns 3 |
trim() |
Removes leading/trailing whitespace | trim(" hi ") returns "hi" |
explode() |
Splits a string into an array | explode(",", "a,b") returns ["a", "b"] |
json_encode() |
Converts data to JSON | json_encode(["ok" => true]) returns {"ok":true} |
password_hash() |
Creates secure password hashes | password_hash("secret", PASSWORD_DEFAULT) |
password_verify() |
Verifies passwords against hashes | password_verify("secret", $hash) |
Helpful Code Snippets
Simple Router
<?php
$path = $_SERVER['REQUEST_URI'];
switch ($path) {
case '/':
echo "Home page";
break;
case '/about':
echo "About page";
break;
default:
http_response_code(404);
echo "Page not found";
}
Security note: To avoid path traversal, only use the path for exact matches or sanitize it before using.
Security Checklist
- Always validate and sanitize input
- Escape output with
htmlspecialchars()when rendering user data - Use prepared statements for all SQL queries
- Never store plain text passwords
- Keep PHP and dependencies updated
Next Steps
Build one small app with these pieces:
- Form input + validation
- MySQL table + PDO insert/select
- Session-based login/logout
That one project will lock in most beginner PHP skills quickly.