DEVELOPER SANDBOX Academy of Mastery
PHP Reference

Modern PHP syntax, requests, PDO, security, cURL, Composer, and application patterns.

Return to sdelgado
REFERENCE GUIDE

PHP Reference

macOS / PHP 8.x
Modern PHP syntax, requests, PDO, security, cURL, Composer, and application patterns.

Core PHP 8.x syntax, types, operators, strings, arrays, and common transformations.

PHP 8.x

01 — Core PHP Syntax & Data

Core PHP Syntax & Data

PHP Tags + Output

<?php
Open a PHP code block.
echo "Hello";
Output a value or string.
print "World";
Output a string using print.
<?= $value ?>
Short echo form commonly used inside templates.
// # /* ... */
PHP supports line comments and block comments.
NOTE
Statements normally end with a semicolon. Pure PHP files commonly omit the closing ?> tag.
Core PHP Syntax & Data

Common Scalar + Special Types

$name = "Ada";
string
$count = 12;
int
$price = 19.95;
float
$active = true;
bool
$value = null;
null
$items = [];
array
$user = new User();
object
Core PHP Syntax & Data

Constants + Inspection

const APP_NAME = "Creative Exchange";
Declare a constant.
define('API_URL', 'https://api.example.com');
Define a constant at runtime.
var_dump($value);
Show type and value while debugging.
print_r($items);
Print readable array/object information.
echo gettype($value);
Read the runtime type name.
Core PHP Syntax & Data

Variables + Operators

=== !== > < >= <=
Comparison operators; strict comparison is preferred when type matters.
&& || !
Boolean operators.
$sum = $a + $b;
Arithmetic and assignment.
$isEqual = ($a === $b);
Strict equality comparison.
$isAllowed = $loggedIn && $active;
Combine boolean conditions.
$count++;
Increment.
$total += 5;
Compound assignment.
Core PHP Syntax & Data

Null + Fallback Patterns

$name = $_GET['name'] ?? 'Guest';
Use a fallback when a value is missing or null.
$userName = $user?->profile?->name;
Null-safe object access.
$status = $code === 200 ? 'ok' : 'error';
Ternary conditional expression.
Core PHP Syntax & Data

Strings

$full = $first . ' ' . $last;
Concatenate strings with the dot operator.
$message = "Welcome, {$full}!";
Interpolate a variable inside a double-quoted string.
strlen($full);
String length.
trim($full);
Remove surrounding whitespace.
strtolower($full);
Convert to lowercase.
strtoupper($full);
Convert to uppercase.
str_contains($full, 'Susan');
Check whether a substring exists.
str_replace('old', 'new', $text);
Replace text.
Core PHP Syntax & Data

Indexed Arrays

$colors = ['red', 'blue', 'green'];
Create an indexed array.
echo $colors[0];
Read by numeric index.
$colors[] = 'gold';
Append a value.
count($colors);
Count items.
in_array('blue', $colors, true);
Check membership using strict comparison.
array_push($colors, 'black');
Append with array_push.
array_pop($colors);
Remove and return the last item.
Core PHP Syntax & Data

Associative Arrays

$user = ['id' => 42, 'name' => 'Ada', 'active' => true];
Create an associative array.
echo $user['name'];
Read a value by key.
$user['role'] = 'admin';
Add or update a keyed value.
array_key_exists('id', $user);
Check whether a key exists.
Core PHP Syntax & Data

Array Transforms

array_column($users, 'name');
Extract one field from each row.
array_filter($users, fn($u) => $u['active']);
Select items that match a condition.
array_map(fn($u) => $u['id'], $users);
Transform each item.
array_merge($a, $b);
Merge arrays.
sort($names);
Sort an indexed array.
NOTE
array_map transforms, array_filter selects, and array_reduce combines values into one result.
Core PHP Syntax & Data

Documentation

Language Reference
Function Search
Search php.net for a function name such as array_filter.

Conditionals, loops, typed functions, closures, project structure, includes, namespaces, and imports.

PHP 8.x

02 — Control Flow, Functions & File Structure

Control Flow, Functions & File Structure

If / Elseif / Else

if ($score >= 90) { ... }
Run a branch when the first condition is true.
elseif ($score >= 80) { ... }
Test another condition when earlier branches fail.
else { ... }
Fallback branch.
Control Flow, Functions & File Structure

Match + Switch

$label = match ($status) { 200 => 'OK', 404 => 'Not Found', default => 'Other' };
match returns a value and uses strict comparison.
switch ($role) { case 'admin': ... break; default: ... }
switch is useful for statement-oriented branching.
Control Flow, Functions & File Structure

Loops

foreach ($users as $user) { ... }
Iterate through arrays or iterable values.
for ($i = 0; $i < 10; $i++) { ... }
Counter-controlled loop.
while ($row = $stmt->fetch()) { ... }
Continue while a fetched row exists.
Control Flow, Functions & File Structure

Functions + Types

function total(float $price, int $qty = 1): float { ... }
Type hints improve readability and catch mistakes.
int $qty = 1
Parameters can have default values.
: float
Return types follow the parameter list.
$result = total(12.50, 2);
Call the function with explicit arguments.
Control Flow, Functions & File Structure

Arrow Functions + Closures

$double = fn(int $n): int => $n * 2;
Compact arrow function.
$withTax = function (float $price) use ($tax) { ... };
Closure importing a variable from the outer scope.
Control Flow, Functions & File Structure

Useful Variable Helpers

isset($value);
Check whether a value exists and is not null.
empty($value);
Check PHP "empty" values; note that 0 and "0" are considered empty.
is_string($value);
Check for a string.
is_array($value);
Check for an array.
is_numeric($value);
Check whether a value is numeric.
filter_var($email, FILTER_VALIDATE_EMAIL);
Validate an email address.
Control Flow, Functions & File Structure

Common Project Structure

public/
Web-facing entry point and public assets.
src/
Application source code.
Controllers/ Models/ Services/
Common application-layer directories.
templates/
View/template files.
config/
Configuration.
storage/
Application-managed storage.
tests/
Automated tests.
vendor/
Composer-installed dependencies.
composer.json
Composer package configuration.
.env
Environment-specific settings; do not commit real secrets.
Control Flow, Functions & File Structure

Include / Require

require __DIR__ . '/config.php';
Stops execution if the file cannot be loaded.
require_once __DIR__ . '/vendor/autoload.php';
Require a file only once.
include __DIR__ . '/partials/header.php';
Emits a warning and continues if the file cannot be loaded.
Control Flow, Functions & File Structure

Namespaces + Imports

namespace App\Services;
Declare a namespace.
use App\Models\User;
Import a class.
use PDO;
Import PDO into the namespace.
class UserService { ... }
Declare a namespaced class.
Control Flow, Functions & File Structure

Documentation

Request input, forms, JSON bodies, response headers, uploads, redirects, and HTTP status codes.

PHP 8.x

03 — Web Requests, Forms & Output

Web Requests, Forms & Output

Request Superglobals

$_GET
Query-string values.
$_POST
Form POST body.
$_FILES
Uploaded files.
$_COOKIE
Cookie values.
$_SESSION
Session data.
$_SERVER
Request and server information.
$_ENV
Environment values.
NOTE
Superglobals are available inside functions without declaring global; treat request values as untrusted input.
Web Requests, Forms & Output

GET Query Example

$q = trim($_GET['q'] ?? '');
Read and normalize a query-string value.
$page = max(1, (int)($_GET['page'] ?? 1));
Read a numeric page value with a minimum of 1.
http_response_code(400);
Return Bad Request when required input is missing.
exit('Missing search term');
Stop the request after returning the error.
Web Requests, Forms & Output

POST Form Example

filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
Read and validate a POSTed email.
if (!$email) { $error = 'Enter a valid email.'; }
Handle validation failure.
Web Requests, Forms & Output

Escape HTML Output

htmlspecialchars($user['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
Escape dynamic HTML output.
Validation
Asks: "Is this acceptable input?"
Escaping
Asks: "Is this safe in this output context?"
Web Requests, Forms & Output

Request Method + Headers

$_SERVER['REQUEST_METHOD']
Read the HTTP request method.
$_SERVER['CONTENT_TYPE'] ?? ''
Read the request Content-Type.
header('Content-Type: application/json');
Send a JSON response content type.
http_response_code(201);
Set Created status.
Web Requests, Forms & Output

Read JSON Request Body

$raw = file_get_contents('php://input');
Read the raw request body.
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
Decode JSON and throw on malformed input.
$name = trim($data['name'] ?? '');
Read a decoded field safely.
Web Requests, Forms & Output

Send JSON Response

header('Content-Type: application/json');
Declare JSON output.
json_encode(['ok' => true, 'data' => $user], JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)
Encode response data.
Web Requests, Forms & Output

File Upload Basics

$_FILES['photo']['error'] === UPLOAD_ERR_OK
Confirm the upload completed successfully.
$_FILES['photo']['tmp_name']
Temporary uploaded-file path.
basename($_FILES['photo']['name'])
Read the submitted filename safely as a basename.
move_uploaded_file($tmp, $destination);
Move an uploaded file into application storage.
PRODUCTION
Generate your own filename; validate MIME/type and size; restrict extensions; keep executable uploads out of web-accessible paths.
Web Requests, Forms & Output

Redirect

header('Location: /dashboard.php');
Send a redirect.
exit;
Stop the script immediately after the redirect.
Web Requests, Forms & Output

Common HTTP Status Codes

200 OK
Successful request.
201 Created
Resource created.
204 No Content
Success with no response body.
400 Bad Request
Malformed or invalid request.
401 Unauthorized
Authentication required.
403 Forbidden
Authenticated but not allowed.
404 Not Found
Requested resource was not found.
422 Unprocessable Content
Validation failure.
500 Internal Server Error
Server-side failure.
Web Requests, Forms & Output

Documentation

Classes, interfaces, enums, exceptions, logging, dates, files, paths, JSON, and environment values.

PHP 8.x

04 — Objects, Exceptions, Files & Utilities

Objects, Exceptions, Files & Utilities

Class + Constructor

class User { ... }
Declare a class.
public function __construct(...)
Constructor; promoted properties can be declared in the parameter list.
public function label(): string { ... }
Typed instance method.
$user = new User(1, 'Ada', 'a@example.com');
Instantiate the class.
Objects, Exceptions, Files & Utilities

Inheritance + Interface

interface Logger { public function log(string $message): void; }
Declare an interface contract.
class FileLogger implements Logger { ... }
Implement an interface.
class AdminUser extends User { ... }
Extend another class.
Objects, Exceptions, Files & Utilities

Static + Enum

public static function make(string $text): string { ... }
Declare a static method.
Slug::make($text)
Call a static method.
enum Role: string { case Admin = 'admin'; case User = 'user'; }
Backed enum with string values.
Objects, Exceptions, Files & Utilities

Exceptions

try { ... }
Run code that may throw.
catch (PDOException $e) { ... }
Handle PDO-specific errors.
catch (Throwable $e) { ... }
Catch broader PHP throwables.
finally { ... }
Optional cleanup that runs after try/catch.
error_log($e->getMessage());
Log exception details instead of exposing them to users.
Objects, Exceptions, Files & Utilities

Throw Your Own Error

throw new InvalidArgumentException('Amount cannot be negative');
Throw a domain-appropriate exception when input is invalid.
Objects, Exceptions, Files & Utilities

Debug + Logging

error_reporting(E_ALL);
Enable all error reporting.
ini_set('display_errors', '1');
Display errors during local development only.
error_log('Reached checkout');
Write a diagnostic message to the error log.
var_dump($value);
Inspect a value during development.
PRODUCTION
Do not display stack traces or sensitive error details to users; log them instead.
Objects, Exceptions, Files & Utilities

Date + Time

$now = new DateTimeImmutable('now');
Create an immutable date/time value.
$tomorrow = $now->modify('+1 day');
Create a modified copy.
$now->format('Y-m-d H:i:s');
Format a date/time.
new DateTimeImmutable($row['created_at']);
Create a date/time from stored data.
Objects, Exceptions, Files & Utilities

Files

file_get_contents($path);
Read an entire file.
file_put_contents($path, $text);
Write a file.
file_put_contents($log, $line, FILE_APPEND);
Append to a file.
file_exists($path);
Check existence.
is_file($path);
Check for a regular file.
is_dir($path);
Check for a directory.
mkdir($dir, 0755, true);
Create nested directories.
unlink($path);
Delete a file.
Objects, Exceptions, Files & Utilities

Path Helpers

__DIR__
Directory of the current file.
__FILE__
Full path of the current file.
$path = __DIR__ . '/data/users.json';
Build a path relative to the current file.
basename($path);
Read the final path component.
dirname($path);
Read the parent directory.
Objects, Exceptions, Files & Utilities

JSON

json_encode($data, JSON_THROW_ON_ERROR);
Encode PHP data to JSON and throw on errors.
json_decode($json, true, 512, JSON_THROW_ON_ERROR);
Decode JSON to an associative array and throw on errors.
Objects, Exceptions, Files & Utilities

Environment Values

getenv('API_KEY');
Read an environment variable.
$_ENV['DATABASE_URL'] ?? null
Read an environment value from $_ENV when available.
NOTE
How .env is loaded depends on the framework/library; never commit real API keys, passwords, or production connection strings.
Objects, Exceptions, Files & Utilities

Documentation

Session state, cookies, password hashing, CSRF protection, secure randomness, and web security defaults.

PHP 8.x

05 — Sessions, Cookies, Passwords & Security

Sessions, Cookies, Passwords & Security

Sessions

session_start();
Start or resume a session before reading or writing $_SESSION.
$_SESSION['user_id'] = $user['id'];
Store a value in the session.
$userId = $_SESSION['user_id'] ?? null;
Read a session value safely.
unset($_SESSION['user_id']);
Remove one session value.
session_destroy();
Destroy the session.
Sessions, Cookies, Passwords & Security

Cookies

setcookie('theme', 'dark', [...]);
Set a cookie with explicit options.
'secure' => true
Send only over HTTPS.
'httponly' => true
Prevent JavaScript access.
'samesite' => 'Lax'
Set SameSite behavior.
$theme = $_COOKIE['theme'] ?? 'light';
Read a cookie with a fallback.
Sessions, Cookies, Passwords & Security

Password Hashing

password_hash($password, PASSWORD_DEFAULT);
Hash a password using PHP's current recommended default algorithm.
password_verify($password, $hash)
Verify a password against its stored hash.
password_needs_rehash($hash, PASSWORD_DEFAULT)
Check whether an existing hash should be upgraded.
RULE
Store password hashes, never original passwords.
Sessions, Cookies, Passwords & Security

CSRF Pattern

$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
Create and store a CSRF token.
hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')
Compare the submitted token safely.
http_response_code(403);
Return Forbidden when the token is invalid.
Sessions, Cookies, Passwords & Security

Generate Secure Random Values

bin2hex(random_bytes(32));
Generate a cryptographically secure token.
random_int(100000, 999999);
Generate a cryptographically secure random integer.
Sessions, Cookies, Passwords & Security

Web Security Checklist

HTML output
Escape dynamic HTML with htmlspecialchars().
Input
Validate expected type, range, and format.
SQL
Use PDO prepared statements for user-supplied values.
Passwords
Hash passwords with password_hash().
HTTPS
Use HTTPS in production.
Cookies
Use Secure, HttpOnly, and SameSite settings where appropriate.
CSRF
Protect state-changing browser requests.
Secrets
Do not expose secrets in Git, HTML, JavaScript, or error pages.
Uploads
Restrict type, size, filename, and destination.
Errors
Return generic production errors and log details server-side.
Sessions, Cookies, Passwords & Security

Do Not Do This

$sql = "SELECT * FROM users WHERE email = '$email'";
SQL injection risk: do not concatenate untrusted values into SQL.
echo $_GET['name'];
XSS risk: do not output unescaped request data.
$apiKey = 'real-production-key';
Secret leak: do not hard-code production credentials.
Sessions, Cookies, Passwords & Security

Documentation

PDO connections, prepared statements, CRUD operations, transactions, and database safety.

PHP 8.x

06 — PDO Database Access for Web Apps

PDO Database Access for Web Apps

Connect - PostgreSQL

new PDO('pgsql:host=localhost;port=5432;dbname=app', $dbUser, $dbPass, [...])
Create a PostgreSQL PDO connection.
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
Throw exceptions for database errors.
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
Fetch rows as associative arrays by default.
PDO Database Access for Web Apps

Connect - MySQL

new PDO('mysql:host=localhost;dbname=app;charset=utf8mb4', $dbUser, $dbPass, [...])
Create a MySQL PDO connection using utf8mb4.
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
Throw exceptions for database errors.
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
Fetch rows as associative arrays by default.
PDO Database Access for Web Apps

Select One Row

$stmt = $pdo->prepare('SELECT id, name, email FROM users WHERE id = :id');
Prepare a SELECT with a named placeholder.
$stmt->execute(['id' => $id]);
Execute with bound data.
$user = $stmt->fetch();
Fetch one row.
PDO Database Access for Web Apps

Select Many Rows

$stmt = $pdo->prepare('SELECT id, name FROM users WHERE active = :active ORDER BY name');
Prepare a filtered multi-row query.
$stmt->execute(['active' => true]);
Execute the query.
$users = $stmt->fetchAll();
Fetch all remaining rows.
PDO Database Access for Web Apps

Insert

$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
Prepare an INSERT.
$stmt->execute(['name' => $name, 'email' => $email]);
Execute with values.
$id = $pdo->lastInsertId();
Read the generated ID where supported.
PDO Database Access for Web Apps

Update + Delete

$pdo->prepare('UPDATE users SET name = :name WHERE id = :id');
Prepare an UPDATE with a WHERE condition.
$stmt->execute(['name' => $name, 'id' => $id]);
Execute the UPDATE.
$pdo->prepare('DELETE FROM users WHERE id = :id');
Prepare a DELETE with a WHERE condition.
$stmt->execute(['id' => $id]);
Execute the DELETE.
PDO Database Access for Web Apps

Transaction

$pdo->beginTransaction();
Start a transaction.
$pdo->commit();
Commit related statements when all succeed.
$pdo->inTransaction()
Check whether a transaction is active.
$pdo->rollBack();
Roll back when an exception occurs.
throw $e;
Re-throw after cleanup when the caller should handle the failure.
PDO Database Access for Web Apps

Prepared Statement Rule

:id :email ?
Use placeholders for complete data values.
RULE
Do not concatenate user input into SQL.
LIMITATION
Placeholders cannot safely stand in for arbitrary SQL identifiers such as table names or ORDER BY columns.
PDO Database Access for Web Apps

Useful PDO Calls

$pdo->prepare($sql)
Create a prepared statement.
$stmt->execute($values)
Execute with values.
$stmt->fetch()
Fetch the next row.
$stmt->fetchAll()
Fetch remaining rows.
$stmt->rowCount()
Affected rows; SELECT behavior varies by driver.
$pdo->lastInsertId()
Last generated ID where supported.
beginTransaction() / commit() / rollBack()
Transaction control methods.
PDO Database Access for Web Apps

Documentation

The cURL request lifecycle, GET requests, headers, status inspection, errors, and request metadata.

PHP 8.x

07 — PHP cURL - The Request Pattern

PHP cURL - The Request Pattern

The Pattern to Remember

$ch = curl_init($url);
1. Create the request handle.
curl_setopt_array($ch, [...]);
2. Set request options.
$response = curl_exec($ch);
3. Execute the request.
curl_getinfo($ch, CURLINFO_HTTP_CODE);
4. Inspect response status and metadata.
curl_error($ch) / curl_errno($ch)
Inspect transport errors.
curl_close($ch);
5. Close the handle or let it go out of scope.
PHP cURL - The Request Pattern

Simple GET

$ch = curl_init('https://api.example.com/users/42');
Initialize the request with a URL.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Return the body as a string instead of printing it.
$response = curl_exec($ch);
Execute the GET request.
json_decode($response, true, 512, JSON_THROW_ON_ERROR);
Decode a JSON response.
curl_close($ch);
Close the handle.
PHP cURL - The Request Pattern

GET with Query Parameters

$query = http_build_query(['q' => 'brown pelican', 'page' => 2, 'limit' => 20]);
Build an encoded query string.
$url = 'https://api.example.com/search?' . $query;
Append the query string to the endpoint.
curl_exec($ch);
Execute the request.
PHP cURL - The Request Pattern

GET with Bearer Token

'Accept: application/json'
Request JSON.
'Authorization: Bearer ' . $token
Send a bearer token.
CURLOPT_HTTPHEADER => [...]
Provide custom request headers.
SECURITY
Send credentials only over HTTPS and keep tokens in environment/config, not committed source.
PHP cURL - The Request Pattern

Useful GET Options

CURLOPT_RETURNTRANSFER => true
Return the response body as a string.
CURLOPT_TIMEOUT => 15
Total timeout in seconds.
CURLOPT_CONNECTTIMEOUT => 5
Connection timeout.
CURLOPT_FOLLOWLOCATION => true
Follow redirects when appropriate.
CURLOPT_HTTPHEADER => [...]
Send custom headers.
PHP cURL - The Request Pattern

Inspect Status + Response

$response = curl_exec($ch);
Transport-level execution.
$response === false
Detect a cURL/network failure.
curl_error($ch)
Read the transport error message.
curl_errno($ch)
Read the transport error number.
curl_getinfo($ch, CURLINFO_HTTP_CODE)
Read the HTTP status code.
$status >= 400
Detect an HTTP error response even when transport succeeded.
PHP cURL - The Request Pattern

Documentation

POST bodies, form data, custom methods, file uploads, and reusable JSON request helpers.

PHP 8.x

08 — cURL POST, JSON, PUT/PATCH/DELETE & Uploads

cURL POST, JSON, PUT/PATCH/DELETE & Uploads

POST JSON

$payload = json_encode([...], JSON_THROW_ON_ERROR);
Encode the request body as JSON.
CURLOPT_POST => true
Send a POST request.
CURLOPT_POSTFIELDS => $payload
Attach the JSON body.
'Content-Type: application/json'
Declare the request body format.
'Accept: application/json'
Request a JSON response.
$response = curl_exec($ch);
Execute the request.
cURL POST, JSON, PUT/PATCH/DELETE & Uploads

POST Form Data

CURLOPT_POSTFIELDS => ['name' => 'Ada', 'email' => 'ada@example.com']
Passing an array creates multipart form data.
http_build_query($data)
Use for application/x-www-form-urlencoded data with the matching content type.
cURL POST, JSON, PUT/PATCH/DELETE & Uploads

PUT / PATCH / DELETE

CURLOPT_CUSTOMREQUEST => 'PATCH'
Set PATCH; use PUT or DELETE for those methods.
CURLOPT_POSTFIELDS => $payload
Attach a request body when needed.
'Content-Type: application/json'
Declare JSON body data.
'Authorization: Bearer ' . $token
Send authorization.
cURL POST, JSON, PUT/PATCH/DELETE & Uploads

Upload a File

new CURLFile($path, mime_content_type($path), basename($path))
Wrap a local file for multipart upload.
CURLOPT_POST => true
Send the upload as POST.
CURLOPT_POSTFIELDS => ['photo' => $file, 'caption' => 'Pelican study']
Attach the file and related form fields.
cURL POST, JSON, PUT/PATCH/DELETE & Uploads

Reusable JSON Request Helper

function requestJson(string $method, string $url, ?array $body = null, array $headers = []): array
Reusable request helper signature.
CURLOPT_CUSTOMREQUEST => $method
Use the requested HTTP method.
CURLOPT_HTTPHEADER => array_merge(['Accept: application/json'], $headers)
Combine default and caller-provided headers.
JSON_THROW_ON_ERROR
Throw for JSON encoding/decoding failures.
curl_error($ch)
Throw on transport failure.
CURLINFO_HTTP_CODE
Return the HTTP status with decoded response data.
NOTE
If sending JSON, include Content-Type: application/json. Production helpers may also need retries, structured errors, tracing, and rate-limit handling.
cURL POST, JSON, PUT/PATCH/DELETE & Uploads

Documentation

PHP CLI commands, local server use, extensions, Composer, package binaries, and troubleshooting.

PHP 8.x

09 — CLI, Composer & Daily Development Commands

CLI, Composer & Daily Development Commands

PHP on macOS Terminal

php -v
Installed PHP version.
php -m
Loaded extensions.
php -i
PHP configuration information.
php -l file.php
Syntax-check a PHP file.
php script.php
Run a PHP script.
php -r 'echo PHP_VERSION;'
Run inline PHP.
php --ini
Locate loaded configuration files.
CLI, Composer & Daily Development Commands

Built-in Dev Server

cd project/public
Enter the web-facing directory.
php -S localhost:8000
Start PHP's built-in development server.
NOTE
The built-in server is for development/testing, not production.
CLI, Composer & Daily Development Commands

Check cURL + PDO Modules

php -m | grep curl
Check whether the cURL extension is loaded.
php -m | grep PDO
Check PDO.
php -m | grep pdo_pgsql
Check the PostgreSQL PDO driver.
php -m | grep pdo_mysql
Check the MySQL PDO driver.
CLI, Composer & Daily Development Commands

Composer Essentials

composer --version
Composer version.
composer init
Create composer.json interactively.
composer install
Install dependencies using composer.lock when present.
composer update
Resolve dependency versions and update the lock file.
composer require vendor/package
Add a runtime dependency.
composer require --dev vendor/package
Add a development dependency.
composer remove vendor/package
Remove a package.
composer dump-autoload
Regenerate autoload files.
composer show
Show installed packages.
composer outdated
Show packages with available updates.
CLI, Composer & Daily Development Commands

Run Package Binaries

./vendor/bin/phpunit
Run PHPUnit when installed.
./vendor/bin/phpstan analyse
Run PHPStan when installed.
./vendor/bin/php-cs-fixer fix
Run PHP CS Fixer when installed.
CLI, Composer & Daily Development Commands

Basic composer.json Idea

"php": "^8.4"
Example PHP version constraint.
"psr-4": { "App\\": "src/" }
Example PSR-4 autoload mapping.
composer.json
Defines package requirements and autoloading.
CLI, Composer & Daily Development Commands

When Something Fails

Syntax error
Run php -l file.php and read the first parser error.
Undefined function
Check spelling and whether the required extension is loaded with php -m.
Class not found
Check namespace/import and run composer dump-autoload.
cURL failure
Inspect curl_errno(), curl_error(), and curl_getinfo().
HTTP API failure
Inspect status code and body; transport success does not imply HTTP success.
PDO failure
Use exception mode, log the exception, and check DSN/credentials/driver.
Blank page in local dev
Enable full error reporting temporarily and check server logs.
CLI, Composer & Daily Development Commands

macOS Package Note

which php
Show which PHP executable the shell will run.
php -v
Confirm the active PHP version.
php --ini
Show active configuration files.
NOTE
On macOS, PHP is commonly managed separately from the OS; extension and configuration paths depend on installation method.
CLI, Composer & Daily Development Commands

Documentation

Common request, endpoint, API-client, database, and security flows worth recognizing quickly.

PHP 8.x

10 — High-Value Patterns to Recognize

High-Value Patterns to Recognize

Typical Request / Controller Flow

require_once __DIR__ . '/../vendor/autoload.php';
Load dependencies.
session_start();
Start session state when required.
filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
Read and validate request input.
http_response_code(400);
Reject invalid input.
$pdo->prepare('SELECT ... WHERE id = :id')
Prepare the database query.
$stmt->execute(['id' => $id]);
Execute with data.
$user = $stmt->fetch();
Read the result.
http_response_code(404);
Return Not Found when no record exists.
require __DIR__ . '/../templates/user.php';
Render the response template.
PATTERN
Input -> validation -> application/database work -> response/template.
High-Value Patterns to Recognize

Typical API Endpoint Flow

header('Content-Type: application/json');
Declare JSON response output.
file_get_contents('php://input')
Read the request body.
json_decode(..., JSON_THROW_ON_ERROR)
Decode JSON and throw on malformed input.
validate -> perform work
Perform application logic after validation.
http_response_code(201);
Return Created on success.
json_encode(['ok' => true], JSON_THROW_ON_ERROR)
Send JSON response.
catch (Throwable $e)
Log failure and return a generic server error.
High-Value Patterns to Recognize

Typical API Client Flow (cURL)

requestJson('POST', $url, $body, $headers)
Call the reusable HTTP client helper.
$result['status'] === 201
Check the HTTP status.
$order = $result['data'];
Use decoded response data.
High-Value Patterns to Recognize

PHP vs cURL

PHP
Server-side language running the application.
PHP cURL extension
One way PHP code can act as an HTTP client and call another server or API.
WHY IT FEELS DIFFERENT
The PHP application has switched roles from receiving a request to sending one.
High-Value Patterns to Recognize

Server Receives vs PHP Sends

Browser -> PHP
Inspect $_GET, $_POST, headers, JSON body, and files.
PHP -> Database
Use PDO and SQL.
PHP -> External API
Use cURL or another HTTP client library.
PHP -> Browser/API client
Send HTML/JSON, headers, and HTTP status.
High-Value Patterns to Recognize

Most-Used Mental Checklist

Input
What data came in?
Validation
Is it present, valid, and authorized?
Escaping
Do I need to escape it now or only when outputting it?
Database
Am I querying the database? Use prepared statements.
External API
Am I calling another API? Build the HTTP request deliberately.
Response
What status code should I return?
Logging
What should be logged if this fails?
Privacy
Could this reveal a secret or user data?
High-Value Patterns to Recognize

Official References