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);NOTEDocumentation
Language ReferenceFunction SearchConditionals, 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.envInclude / 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
ComposerRequest 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$_ENVNOTEGET 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')ValidationEscapingRequest 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);PRODUCTIONRedirect
header('Location: /dashboard.php');exit;Common HTTP Status Codes
200 OK201 Created204 No Content400 Bad Request401 Unauthorized403 Forbidden404 Not Found422 Unprocessable Content500 Internal Server ErrorDocumentation
Web FeaturesClasses, 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);PRODUCTIONDate + 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'] ?? nullNOTEDocumentation
Function ReferenceObject-Oriented PHPSessions
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)RULECSRF 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 outputInputSQLPasswordsHTTPSCookiesCSRFSecretsUploadsErrorsDo Not Do This
$sql = "SELECT * FROM users WHERE email = '$email'";echo $_GET['name'];$apiKey = 'real-production-key';Documentation
PHP SecurityPDO 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_EXCEPTIONPDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOCConnect - MySQL
new PDO('mysql:host=localhost;dbname=app;charset=utf8mb4', $dbUser, $dbPass, [...])PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTIONPDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOCSelect 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 ?RULELIMITATIONUseful PDO Calls
$pdo->prepare($sql)$stmt->execute($values)$stmt->fetch()$stmt->fetchAll()$stmt->rowCount()$pdo->lastInsertId()beginTransaction() / commit() / rollBack()Documentation
PDO::prepareThe 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 ' . $tokenCURLOPT_HTTPHEADER => [...]SECURITYInspect Status + Response
$response = curl_exec($ch);$response === falsecurl_error($ch)curl_errno($ch)curl_getinfo($ch, CURLINFO_HTTP_CODE)$status >= 400Documentation
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 => trueCURLOPT_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 ' . $tokenUpload a File
new CURLFile($path, mime_content_type($path), basename($path))CURLOPT_POST => trueCURLOPT_POSTFIELDS => ['photo' => $file, 'caption' => 'Pelican study']Reusable JSON Request Helper
function requestJson(string $method, string $url, ?array $body = null, array $headers = []): arrayCURLOPT_CUSTOMREQUEST => $methodCURLOPT_HTTPHEADER => array_merge(['Accept: application/json'], $headers)JSON_THROW_ON_ERRORcurl_error($ch)CURLINFO_HTTP_CODENOTEDocumentation
CURLFilecurl_setopt_arrayPHP CLI commands, local server use, extensions, Composer, package binaries, and troubleshooting.
09 — CLI, Composer & Daily Development Commands
PHP on macOS Terminal
php -vphp -mphp -iphp -l file.phpphp script.phpphp -r 'echo PHP_VERSION;'php --iniBuilt-in Dev Server
cd project/publicphp -S localhost:8000NOTECheck cURL + PDO Modules
php -m | grep curlphp -m | grep PDOphp -m | grep pdo_pgsqlphp -m | grep pdo_mysqlComposer Essentials
composer --versioncomposer initcomposer installcomposer updatecomposer require vendor/packagecomposer require --dev vendor/packagecomposer remove vendor/packagecomposer dump-autoloadcomposer showcomposer outdatedRun Package Binaries
./vendor/bin/phpunit./vendor/bin/phpstan analyse./vendor/bin/php-cs-fixer fixBasic composer.json Idea
"php": "^8.4""psr-4": { "App\\": "src/" }composer.jsonWhen Something Fails
Syntax errorUndefined functionClass not foundcURL failureHTTP API failurePDO failureBlank page in local devmacOS Package Note
which phpphp -vphp --iniNOTEDocumentation
PHP on macOSComposerCommon 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';PATTERNTypical API Endpoint Flow
header('Content-Type: application/json');file_get_contents('php://input')json_decode(..., JSON_THROW_ON_ERROR)validate -> perform workhttp_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
PHPPHP cURL extensionWHY IT FEELS DIFFERENTServer Receives vs PHP Sends
Browser -> PHPPHP -> DatabasePHP -> External APIPHP -> Browser/API clientMost-Used Mental Checklist
InputValidationEscapingDatabaseExternal APIResponseLoggingPrivacyOfficial References
PHP ManualPDO ManualcURL ManualComposer DocsSupported PHP VersionsPHP Releases