Core PHP 8.x syntax, types, operators, strings, arrays, and common transformations.
01 — Core PHP Syntax & Data
Common Scalar + Special Types
$name = "Ada";
$count = 12;
$price = 19.95;
$active = true;
$value = null;
$items = [];
$user = new User();
Constants + Inspection
const APP_NAME = "Creative Exchange";
define('API_URL', 'https://api.example.com');
var_dump($value);
print_r($items);
echo gettype($value);
Variables + Operators
=== !== > < >= <=
&& || !
$sum = $a + $b;
$isEqual = ($a === $b);
$isAllowed = $loggedIn && $active;
$count++;
$total += 5;
Null + Fallback Patterns
$name = $_GET['name'] ?? 'Guest';
$userName = $user?->profile?->name;
$status = $code === 200 ? 'ok' : 'error';
Strings
$full = $first . ' ' . $last;
$message = "Welcome, {$full}!";
strlen($full);
trim($full);
strtolower($full);
strtoupper($full);
str_contains($full, 'Susan');
str_replace('old', 'new', $text);
Indexed Arrays
$colors = ['red', 'blue', 'green'];
echo $colors[0];
$colors[] = 'gold';
count($colors);
in_array('blue', $colors, true);
array_push($colors, 'black');
array_pop($colors);
Associative Arrays
$user = ['id' => 42, 'name' => 'Ada', 'active' => true];
echo $user['name'];
$user['role'] = 'admin';
array_key_exists('id', $user);
Array Transforms
array_column($users, 'name');
array_filter($users, fn($u) => $u['active']);
array_map(fn($u) => $u['id'], $users);
array_merge($a, $b);
sort($names);
NOTE
Documentation
Language Reference
Function Search
Conditionals, loops, typed functions, closures, project structure, includes, namespaces, and imports.
02 — Control Flow, Functions & File Structure
If / Elseif / Else
if ($score >= 90) { ... }
elseif ($score >= 80) { ... }
else { ... }
Match + Switch
$label = match ($status) { 200 => 'OK', 404 => 'Not Found', default => 'Other' };
switch ($role) { case 'admin': ... break; default: ... }
Loops
foreach ($users as $user) { ... }
for ($i = 0; $i < 10; $i++) { ... }
while ($row = $stmt->fetch()) { ... }
Functions + Types
function total(float $price, int $qty = 1): float { ... }
int $qty = 1
: float
$result = total(12.50, 2);
Arrow Functions + Closures
$double = fn(int $n): int => $n * 2;
$withTax = function (float $price) use ($tax) { ... };
Useful Variable Helpers
isset($value);
empty($value);
is_string($value);
is_array($value);
is_numeric($value);
filter_var($email, FILTER_VALIDATE_EMAIL);
Common Project Structure
public/
src/
Controllers/ Models/ Services/
templates/
config/
storage/
tests/
vendor/
composer.json
.env
Include / Require
require __DIR__ . '/config.php';
require_once __DIR__ . '/vendor/autoload.php';
include __DIR__ . '/partials/header.php';
Namespaces + Imports
namespace App\Services;
use App\Models\User;
use PDO;
class UserService { ... }
Documentation
Composer
Request input, forms, JSON bodies, response headers, uploads, redirects, and HTTP status codes.
03 — Web Requests, Forms & Output
Request Superglobals
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_SERVER
$_ENV
NOTE
GET Query Example
$q = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
http_response_code(400);
exit('Missing search term');
POST Form Example
filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email) { $error = 'Enter a valid email.'; }
Escape HTML Output
htmlspecialchars($user['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
Validation
Escaping
Request Method + Headers
$_SERVER['REQUEST_METHOD']
$_SERVER['CONTENT_TYPE'] ?? ''
header('Content-Type: application/json');
http_response_code(201);
Read JSON Request Body
$raw = file_get_contents('php://input');
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$name = trim($data['name'] ?? '');
Send JSON Response
header('Content-Type: application/json');
json_encode(['ok' => true, 'data' => $user], JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)
File Upload Basics
$_FILES['photo']['error'] === UPLOAD_ERR_OK
$_FILES['photo']['tmp_name']
basename($_FILES['photo']['name'])
move_uploaded_file($tmp, $destination);
PRODUCTION
Redirect
header('Location: /dashboard.php');
exit;
Common HTTP Status Codes
200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
422 Unprocessable Content
500 Internal Server Error
Documentation
Web Features
Classes, interfaces, enums, exceptions, logging, dates, files, paths, JSON, and environment values.
04 — Objects, Exceptions, Files & Utilities
Class + Constructor
class User { ... }
public function __construct(...)
public function label(): string { ... }
$user = new User(1, 'Ada', 'a@example.com');
Inheritance + Interface
interface Logger { public function log(string $message): void; }
class FileLogger implements Logger { ... }
class AdminUser extends User { ... }
Static + Enum
public static function make(string $text): string { ... }
Slug::make($text)
enum Role: string { case Admin = 'admin'; case User = 'user'; }
Exceptions
try { ... }
catch (PDOException $e) { ... }
catch (Throwable $e) { ... }
finally { ... }
error_log($e->getMessage());
Throw Your Own Error
throw new InvalidArgumentException('Amount cannot be negative');
Debug + Logging
error_reporting(E_ALL);
ini_set('display_errors', '1');
error_log('Reached checkout');
var_dump($value);
PRODUCTION
Date + Time
$now = new DateTimeImmutable('now');
$tomorrow = $now->modify('+1 day');
$now->format('Y-m-d H:i:s');
new DateTimeImmutable($row['created_at']);
Files
file_get_contents($path);
file_put_contents($path, $text);
file_put_contents($log, $line, FILE_APPEND);
file_exists($path);
is_file($path);
is_dir($path);
mkdir($dir, 0755, true);
unlink($path);
Path Helpers
__DIR__
__FILE__
$path = __DIR__ . '/data/users.json';
basename($path);
dirname($path);
JSON
json_encode($data, JSON_THROW_ON_ERROR);
json_decode($json, true, 512, JSON_THROW_ON_ERROR);
Environment Values
getenv('API_KEY');
$_ENV['DATABASE_URL'] ?? null
NOTE
Documentation
Function Reference
Object-Oriented PHP
Sessions
session_start();
$_SESSION['user_id'] = $user['id'];
$userId = $_SESSION['user_id'] ?? null;
unset($_SESSION['user_id']);
session_destroy();
Regenerate After Login
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
Password Hashing
password_hash($password, PASSWORD_DEFAULT);
password_verify($password, $hash)
password_needs_rehash($hash, PASSWORD_DEFAULT)
RULE
CSRF Pattern
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')
http_response_code(403);
Generate Secure Random Values
bin2hex(random_bytes(32));
random_int(100000, 999999);
Web Security Checklist
HTML output
Input
SQL
Passwords
HTTPS
Cookies
CSRF
Secrets
Uploads
Errors
Do Not Do This
$sql = "SELECT * FROM users WHERE email = '$email'";
echo $_GET['name'];
$apiKey = 'real-production-key';
Documentation
PHP Security
PDO connections, prepared statements, CRUD operations, transactions, and database safety.
06 — PDO Database Access for Web Apps
Connect - PostgreSQL
new PDO('pgsql:host=localhost;port=5432;dbname=app', $dbUser, $dbPass, [...])
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
Connect - MySQL
new PDO('mysql:host=localhost;dbname=app;charset=utf8mb4', $dbUser, $dbPass, [...])
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
Select One Row
$stmt = $pdo->prepare('SELECT id, name, email FROM users WHERE id = :id');
$stmt->execute(['id' => $id]);
$user = $stmt->fetch();
Select Many Rows
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE active = :active ORDER BY name');
$stmt->execute(['active' => true]);
$users = $stmt->fetchAll();
Insert
$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
$stmt->execute(['name' => $name, 'email' => $email]);
$id = $pdo->lastInsertId();
Update + Delete
$pdo->prepare('UPDATE users SET name = :name WHERE id = :id');
$stmt->execute(['name' => $name, 'id' => $id]);
$pdo->prepare('DELETE FROM users WHERE id = :id');
$stmt->execute(['id' => $id]);
Transaction
$pdo->beginTransaction();
$pdo->commit();
$pdo->inTransaction()
$pdo->rollBack();
throw $e;
Prepared Statement Rule
:id :email ?
RULE
LIMITATION
Useful PDO Calls
$pdo->prepare($sql)
$stmt->execute($values)
$stmt->fetch()
$stmt->fetchAll()
$stmt->rowCount()
$pdo->lastInsertId()
beginTransaction() / commit() / rollBack()
Documentation
PDO::prepare
The cURL request lifecycle, GET requests, headers, status inspection, errors, and request metadata.
07 — PHP cURL - The Request Pattern
The Pattern to Remember
$ch = curl_init($url);
curl_setopt_array($ch, [...]);
$response = curl_exec($ch);
curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_error($ch) / curl_errno($ch)
curl_close($ch);
Simple GET
$ch = curl_init('https://api.example.com/users/42');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
json_decode($response, true, 512, JSON_THROW_ON_ERROR);
curl_close($ch);
GET with Query Parameters
$query = http_build_query(['q' => 'brown pelican', 'page' => 2, 'limit' => 20]);
$url = 'https://api.example.com/search?' . $query;
curl_exec($ch);
GET with Bearer Token
'Accept: application/json'
'Authorization: Bearer ' . $token
CURLOPT_HTTPHEADER => [...]
SECURITY
Inspect Status + Response
$response = curl_exec($ch);
$response === false
curl_error($ch)
curl_errno($ch)
curl_getinfo($ch, CURLINFO_HTTP_CODE)
$status >= 400
Documentation
POST bodies, form data, custom methods, file uploads, and reusable JSON request helpers.
08 — cURL POST, JSON, PUT/PATCH/DELETE & Uploads
POST JSON
$payload = json_encode([...], JSON_THROW_ON_ERROR);
CURLOPT_POST => true
CURLOPT_POSTFIELDS => $payload
'Content-Type: application/json'
'Accept: application/json'
$response = curl_exec($ch);
POST Form Data
CURLOPT_POSTFIELDS => ['name' => 'Ada', 'email' => 'ada@example.com']
http_build_query($data)
PUT / PATCH / DELETE
CURLOPT_CUSTOMREQUEST => 'PATCH'
CURLOPT_POSTFIELDS => $payload
'Content-Type: application/json'
'Authorization: Bearer ' . $token
Upload a File
new CURLFile($path, mime_content_type($path), basename($path))
CURLOPT_POST => true
CURLOPT_POSTFIELDS => ['photo' => $file, 'caption' => 'Pelican study']
Reusable JSON Request Helper
function requestJson(string $method, string $url, ?array $body = null, array $headers = []): array
CURLOPT_CUSTOMREQUEST => $method
CURLOPT_HTTPHEADER => array_merge(['Accept: application/json'], $headers)
JSON_THROW_ON_ERROR
curl_error($ch)
CURLINFO_HTTP_CODE
NOTE
Documentation
CURLFile
curl_setopt_array
PHP CLI commands, local server use, extensions, Composer, package binaries, and troubleshooting.
09 — CLI, Composer & Daily Development Commands
PHP on macOS Terminal
php -v
php -m
php -i
php -l file.php
php script.php
php -r 'echo PHP_VERSION;'
php --ini
Built-in Dev Server
cd project/public
php -S localhost:8000
NOTE
Check cURL + PDO Modules
php -m | grep curl
php -m | grep PDO
php -m | grep pdo_pgsql
php -m | grep pdo_mysql
Composer Essentials
composer --version
composer init
composer install
composer update
composer require vendor/package
composer require --dev vendor/package
composer remove vendor/package
composer dump-autoload
composer show
composer outdated
Run Package Binaries
./vendor/bin/phpunit
./vendor/bin/phpstan analyse
./vendor/bin/php-cs-fixer fix
Basic composer.json Idea
"php": "^8.4"
"psr-4": { "App\\": "src/" }
composer.json
When Something Fails
Syntax error
Undefined function
Class not found
cURL failure
HTTP API failure
PDO failure
Blank page in local dev
macOS Package Note
which php
php -v
php --ini
NOTE
Documentation
PHP on macOS
Composer
Common request, endpoint, API-client, database, and security flows worth recognizing quickly.
10 — High-Value Patterns to Recognize
Typical Request / Controller Flow
require_once __DIR__ . '/../vendor/autoload.php';
session_start();
filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
http_response_code(400);
$pdo->prepare('SELECT ... WHERE id = :id')
$stmt->execute(['id' => $id]);
$user = $stmt->fetch();
http_response_code(404);
require __DIR__ . '/../templates/user.php';
PATTERN
Typical API Endpoint Flow
header('Content-Type: application/json');
file_get_contents('php://input')
json_decode(..., JSON_THROW_ON_ERROR)
validate -> perform work
http_response_code(201);
json_encode(['ok' => true], JSON_THROW_ON_ERROR)
catch (Throwable $e)
Typical API Client Flow (cURL)
requestJson('POST', $url, $body, $headers)
$result['status'] === 201
$order = $result['data'];
PHP vs cURL
PHP
PHP cURL extension
WHY IT FEELS DIFFERENT
Server Receives vs PHP Sends
Browser -> PHP
PHP -> Database
PHP -> External API
PHP -> Browser/API client
Most-Used Mental Checklist
Input
Validation
Escaping
Database
External API
Response
Logging
Privacy
Official References
PHP Manual
PDO Manual
cURL Manual
Composer Docs
Supported PHP Versions
PHP Releases