Anki Cards: PHP Core Terminology
PHP Terminology (Core Concepts) 🧠
In a web context, aA single execution of PHP execution that respondscode to onerespond to an HTTP request (or CLI run) is often called a {{c1::request}script}} (or a {{c2::script run}request}}).
- PHP is
primarilytypically executed by an {{c1::interpreted}interpreter}} language (executed by the {{c2::PHP engine}}), not compiled ahead-of-time like C/C++.
- PHP is a {{c1::server-side}}
: language: the browser receives the {{c2::output}} (e.g., HTML/JSON), not your PHP {{c3::sourcePHP code}source}}.
- PHP
“can run in {{c1::superglobals}web server mode}}” are(responding built-into variablesHTTP) availableor in any scope, e.g. {{c2::$GET}CLI}} (command line).
PHP’s execution model is usually {{c1::stateless per request}}; to persist data across requests you need {{c2::sessions}}, {{c3::
$POST}cookies}},
or a {{c4:
:database}}.
In modern PHP, you typically install libraries using {{c1::Composer}} and load them via {{c2::autoloading}}.
Superglobals & HTTP Basics 🌐
The superglobal for query-string parameters is {{c1::$_GET}}.
The superglobal for form-body parameters (common with POST forms) is {{c1::$_POST}}.
Request metadata (method, headers info, paths, etc.) is found in {{c1::$_SERVER}}.
“TypeUploaded juggling”file meansmetadata PHPlives mayin {{c1::
automatically$_FILES}}.
convert}}Cookie values
betweenare typesin (e.g.,{{c1::$COOKIE}}; stringserver-side ↔session int)data duringis in {{c2::comparisons}$SESSION}}
or operations.
With declare(strict_types=1);, scalar type hints become more(after {{
c1:c3::
strict}session_start()}
(fewer implicit {{c2::conversions}}).
ValidationA answers:common safe-read pattern is: \$q = \$_GET['q'] {{c1::??}} '' (null-coalescing default).
To redirect a browser you use {{c1::header(‚Location: …‘)}} and then immediately call {{c2::exit}}.
You can set the HTTP status code in PHP using {{c1::http_response_code(404)}} (or another code).
Security Essentials (Validation, Sanitization, Escaping) 🛡️
“Is this
input allowed?”
}} ✅ (reject invalid), while sanitization answers: {{c2::“Can we clean/transform it?”}} 🧼.
Escaping means making output safe for a specific {{c1::context}} (HTML/attribute/URL/JS), typically done {{c2::right before output}}.
A {{c1::namespace}} helps prevent {{c2::naming collisions}} by qualifying identifiers like MyApp\Tools\Mailer.
“Dependency injection (DI)” means you {{c1::pass dependencies in}} (e.g., via constructor) instead of {{c2::creating them inside}}.
An “autoload” mechanism loads class files when a class is {{c1::
referenced}validation}}
,; often“make viait Composer’scleaner/safer” is {{c2::
PSR-4}sanitization}}
; mapping.“make it safe to display” is {{c3::escaping}}.
PDOPreventing isXSS aprimarily database interface that supportsrequires {{c1::
preparedescaping statements}}on to reduce {{c2::SQL injection}} risk.
Security Concepts (XSS / CSRF / SQLi)
XSS often happens when you output untrusted data without proper {{c1::escaping}output}} in the correct
{{c2::context}}context (HTML, attribute, JS, URL).
CSRFThe is a forged request from another site; mitigation usually requires a per-request {{c1::token}} (WordPress: {{c2::nonce}}).
SQL injection risk increases when you build queries via string {{c1::concatenation}}; safer: {{c2::prepared statements}} with bound parameters.
A secure default: {{c1::validate input}}, then {{c2::sanitize if needed}}, and finally {{c3::escape on output}} 🛡️.
Passwords should be stored using {{c1::password_hash}} (not plain text, not fast hashes like {{c2::MD5}}).
To check a password, use {{c1::password_verify}} against the stored {{c2::hash}}.
Ingo-to HTML
context, a common safe-escapeescaping function is {{c1::htmlspecialchars}} with flags like {{c2::ENT_QUOTES}} and encoding {{c3::UTF-8}}.
AfterSQL sendingInjection ais redirectprevented header,by you should usually callusing {{c1::
exit}prepared statements}}
to(e.g., prevent furthervia {{c2::
output}PDO}}
.) instead of string concatenation.
Language Constructs: Output & Debugging
echoCSRF is
amitigated language construct used tousing {{c1::
output}anti-CSRF tokens}}
text; it does(WordPress: {{c2::
not return}} a value.
print outputs text and returns {{c1::1}} (so it can be used in {{c2::expressions}nonces}}).
var_dump($x)Passwords shows both {{c1::type}} and {{c2::value}} (great for debugging).
print_r($x, true) returns a {{c1::string}} representation instead of {{c2::printing}} it.
die() is an alias of {{c1::exit()}} and stops script {{c2::execution}} immediately.
Including Files & Autoloading
require 'file.php'; causes a {{c1::fatal error}} if the file is missing; include typically emits a {{c2::warning}}.
require_once / include_once prevent loading the same file {{c1::more than once}} in a single {{c2::request}}.
A common Composer autoload entrypoint is require {{c1::__DIR__}} . {{c2::'/vendor/autoload.php'}}; ⚙️
Control Flow (Conditionals, match, Loops)
if / elseif / else chooses a branch based on a {{c1::boolean condition}}.
switch compares a single expression against multiple {{c1::cases}} and typically needs {{c2::break}} to avoid fall-through.
match is an expression that {{c1::returns a value}} and uses {{c2::strict comparison}} semantics.
foreach ($arr as $value) iterates over {{c1::values}}; foreach ($arr as $k => $v) gives both {{c2::keys}} and values.
break exits the current {{c1::loop}} (or switch); continue skips to the {{c2::next iteration}}.
for is good when you know the {{c1::index range}}; while continues as long as a {{c2::condition}} is true.
Functions & Scope
A function definition looks like function name($a, $b = 123): int { {{c1::return}} ... }.
A parameter with = ... is a {{c1::default argument}}, used when the caller omits that {{c2::parameter}}.
Variables declared inside a function are {{c1::local}} by default (not visible {{c2::outside}}).
global $x; pulls a variable from the {{c1::global scope}} into the function (use {{c2::sparingly}}).
A static $count = 0; inside a function persists its value between {{c1::calls}} within the same {{c2::request}}.
Anonymous functions are created with function (...) { ... } and canshould be stored
in a {{c1::variable}} as a {{c2::callable}}.
To import outer variables into a closure, use function () use ($x) { ... } (captures by {{c1::value}} by default).
Error Handling (Exceptions)
Exception flow: try { ... } catch (Throwable $e) { ... } finally { ... } where finally runs {{c1::even if an exception occurs}}.
throw new Exception('msg'); interrupts normal flow and transfers control to a matching {{c1::catch}} block.
Throwable is the interface implemented by both {{c1::Exception}} and {{c2::Error}} types.
Variables, Types, Constants
PHP variables start with {{c1::
$}} (e.g., \$name = 'Ada';).
Common scalar types: {{c1::int}}, {{c2::float}}, {{c3::string}}, {{c4::bool}}.
null represents an {{c1::absence of value}}; isset($x) is false if $x is {{c2::null}} or undefined.
Two common ways to define constants: define('X', 'y') and {{c1::const}} X = 'y';.
const is evaluated at {{c1::compile time}password_hash}} and
is often used in {{c2::classes}}.
Operators (Daily Drivers)
String concatenation uses . and concatenation assignment uses {{c1::.=}}.
“Loose” comparisons use {{c1::==}} (type juggling); “strict” comparisons use {{c2::===}} (type + value).
The spaceship operator <=> returns {{c1::-1}}, {{c2::0}}, or {{c3::1}} depending on ordering.
Null coalescing: \$x = \$maybe ?? 'default'; uses 'default' if $maybe is {{c1::null}} or {{c2::unset}}.
Nullsafe operator: \$user?->profile?->email stops and yields {{c1::null}} if an intermediate is {{c2::null}}.
Ternary operator: \$label = \$ok ? 'Yes' : 'No'; chooses between {{c1::two values}} based on a {{c2::condition}}.
Strings (Quoting, Interpolation, Utilities)
In single quotes 'Hello \$name', variables are {{c1::not interpolated}}.
In double quotes "Hello \$name", variables are {{c1::interpolated}} (replaced with their {{c2::values}}).
strlen($s) returns the string’s {{c1::length}} (bytes; for multibyte use {{c2::mb_strlen}}).
strpos($haystack, $needle) returns the position or {{c1::false}} (so comparechecked with {{c2::
===password_verify}}—never false}}with carefully).plain hashing like MD5.
trim($s)A removessecure whitespacemindset rule: never trust types from
{{c1::both ends}}; ltrim and rtrim remove from {{c2::one side}}.
explode(',', $s) converts string → {{c1::array}}; implode(',', $arr) converts array → {{c2::string}}.
sprintf('Hi %s, you have %d', $name, $count) formats text with {{c1::placeholders}}.
Arrays (Creation, Access, Common Tools)
Indexed arrays look like \$a = [10, 20, 30]; while associative arrays look like \$u = ['name' => 'Ada']; (keys are {{c1::strings}}).
Append to an array with \$a[] = 99; (auto-increments the {{c1::next index}}).
count($arr) returns the number of {{c1::elements}}.
in_array($needle, $haystack) checks for a value; for strict checking use in_array(..., ..., {{c1::true}}).
array_key_exists('k', $arr) checks if a {{c1::key exists}} (even if value is {{c2::null}}).
array_map($fn, $arr) transforms each element into a new {{c1::array}}.
array_filter($arr, $fn) keeps elements where the callback returns {{c1::true}}.
array_reduce($arr, $fn, $initial) folds the array into a single {{c1::value}}.
array_merge($a, $b) combines arrays; numeric keys are {{c1::reindexed}} by default.
Sorting: sort($arr) sorts values and reindexes; asort($arr) preserves {{c1::keys}}.
HTTP & Superglobals
Query-string parameters are in {{c1::$
GET}}, form body fields are in /{{c2::$POST}}
; always {{c3::validate}} and {{c4::cast/allowlist}}.
PHP Output & Debugging 🧪
RequestThe metadatamost (method,common headersway info,to pathoutput info)text is
in {{c1::
$_SERVER}echo}} (a language construct).
print is similar to echo but it {{c1::returns}} {{c2::1}}.
UploadedFor filetype metadata+ isvalue in {{c1::$_FILES}} (name/type/tmp_name/error/size).
Sessionsdebugging, use {{c1::
var_dump($
_SESSION}x)}
,}.
butFor youreadable mustarray/object calloutput, use {{c1::print_r($x)}} (optionally with {{c2::
session_start()}true}}
first.to return the string).
ATo safestop readexecution pattern:immediately, \$q = \$_GET['q'] ?? ''; uses ause {{c1::
default}die()}}
when the key isor {{c2::
missing}exit()}}.
Redirects are sent with header('Location: /path'); and should be followed by {{c1::exit}}.
Set an HTTP status with http_response_code({{c1::404}}); (or other codes).
“Headers
mustalready besent” senterrors beforeoften anyoccur because you produced {{c1::output}} (even
straywhitespace) whitespace),before otherwisecalling you’ll get “{{c2::
headers already sent}header()}
”}.
OOPIncludes Essentials& (Classes,File Visibility,Loading Traits)📁
CreateIf ana objectfile withis newmissing, {{c1::ClassName}require}}() andtriggers access instance members witha {{c2::$this->fatal error}}, while {{c3::include}}. only raises a warning and continues.
Visibility:To publicensure (anywhere),a protectedfile (classis +loaded subclasses),at privatemost ({{c1::classonce, only}}).
Inheritance usesuse {{c1::
extends}require_once}}
; interfaces useor {{c2::
implements}}.
An abstract class can’t be {{c1::instantiated}} and may contain abstract methods that must be {{c2::implemented}include_once}}.
A
traitbest-practice allowsfor horizontalpaths codeis reuse via useusing {{c1::TraitName}DIR};.
Static members belong} to
thebuild {{c1::class}}absolute-ish (not the instance) and are accessed with {{c2::ClassName::}}.
Composer (Modern PHP Workflow)
composer.json describes dependencies and autoload rules; composer.lock pins {{c1::exact versions}}.
Install dependencies with composer {{c1::install}}; update dependencies with composer {{c2::update}}.
PSR-4 autoloading maps a namespace prefix to a {{c1::directory}}paths (e.g.,
App\require →__DIR__ {{c2::src/}}. '/vendor/autoload.php';).
PDO Database Snippets (Practical)
A PDO DSN for MySQL often includes charset={{c1::utf8mb4}} to support full Unicode.
Enable exceptions for PDO with PDO::ATTR_ERRMODE => PDO::ERRMODE_{{c1::EXCEPTION}}.
Prepared statement flow: prepare() then {{c1::execute()}} then fetch()/fetchAll().
fetch(PDO::FETCH_ASSOC) returns one row as an associative {{c1::array}}.
lastInsertId() returns the last generated {{c1::AUTO_INCREMENT}} value for the current connection.
Parameter binding uses placeholders like :email, and values are provided as an {{c1::array}} to execute().
WordPress Parallels (If You Use WP)
WordPress “actions” run code at a hook point via {{c1::add_action}}; “filters” modify a value via {{c2::add_filter}}.
Common WP escaping helpers: esc_html(), esc_attr(), and {{c1::esc_url()}}.
Common WP sanitizers: sanitize_text_field() and {{c1::sanitize_email()}}.
WP nonces help mitigate {{c1::CSRF}} via functions like wp_nonce_field() and {{c2::check_admin_referer()}}.
WP database safety uses \$wpdb->{{c1::prepare}}(...) to safely insert variables into queries.
Common Gotchas & “Sticky” Reminders
Prefer the full opening tag {{c1::<?php}} over short tags <? for portability.
In
“pure
PHPPHP” files, it’s common to omit the closing tag
{{c1::?>}} to
avoidprevent accidental whitespace output.
In
PHP,
theControl stringFlow {{c1::'0'}}(Conditionals is& falsy,Loops) so🔁
use {{c2::strict comparisons}} when it matters.
isset($x)A isstandard falseconditional when $xchain is {{c1::null}if}}; empty($x) is true for values like '', 0, '0', [], and→ {{c2::null}elseif}} → {{c3::else}}.
===switch comparesrequires bothexplicit {{c1::type}break}} andto value; use it especially when functions can returnavoid {{c2::false}fall-through}} (e.g., strpos).
Output buffering can delay output; ob_start()match begins(PHP buffering8+) andis ob_end_flush()an {{c1::sends}expression}} thethat buffer.{{c2::returns a value}} and uses {{c3::strict comparison}}.
UseThe filter_var($email,most FILTER_VALIDATE_EMAIL)common toloop for arrays is {{c1::validate}foreach}} an email (returns the value or {{c2::false}}).
UseTo filter_input(INPUT_GET,get 'id',both FILTER_VALIDATE_INT) to validate external inputkey and avoidvalue directin use of {{c1::superglobals}} (optional style).
When handling file uploads, always check \$_FILES['x']['error'] === {{c1::UPLOAD_ERR_OK}} before moving the file.
Move an uploaded file safely with {{c1::move_uploaded_file}}($tmp, $destination) (not rename).
Bonus: Mini “Code Shape” Clozes (Fast Recall)
Minimal safe redirect pattern: header('Location: /x'); {{c1::exit;}}
Minimal HTML escaping pattern: echo htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, '{{c1::UTF-8}}');
Minimal null default pattern: \$name = \$_GET['name'] {{c1::??}} 'Guest';
Minimal foreach with key/value:foreach: foreach (\$arr as {{c1::\$k}} => {{c2::\$v}}) { ... }.
Minimalbreak try/catch:exits a loop; {{c1::continue}} skips to the next iteration.
A do { ... } while (...); loop runs the body at least {{c1::once}}.
Functions & Scope 🧩
A function can declare a return type using function f(): {{c1::int}} { ... }.
Function parameters can have defaults like function f(\$x = {{c1::123}}).
Variables inside a function are local unless declared {{c1::global}} (use sparingly).
A static local variable in a function {{c1::persists between calls}}.
In PHP, functions can be {{c1::passed as callables}} (e.g., to array_map).
Anonymous functions use function() {}; arrow functions use {{c1::fn}}(\$x) => ... (short syntax).
Errors & Exceptions 🚨
Exception handling uses try { ... } catch ({{c1::Throwable}} \$e) { ... } finally { ... }.
MinimalYou PDOcan selectraise pattern:an exception with {{c1::throw}} new Exception('message');.
finally runs whether an exception is thrown or not: it’s ideal for {{c1::cleanup}}.
In production, you generally {{c1::log errors}} rather than displaying them to users.
Variables, Types, and “Type Juggling” 🧱
PHP variables start with the symbol {{c1::$}}.
PHP supports “type juggling,” meaning it may {{c1::auto-convert}} types (string ↔ int, etc.).
To enforce stricter scalar type checking, add {{c1::declare(strict_types=1);}} at the top of a file.
Common scalar types are {{c1::int}}, {{c2::float}}, {{c3::string}}, {{c4::bool}}.
The special type representing “no value” is {{c1::null}}.
To cast to integer, use {{c1::(int)}}\$x; to cast to string, use {{c2::(string)}}\$x.
A notorious truthiness gotcha: the string {{c1::'0'}} is {{c2::falsy}} in PHP.
Operators & Comparisons ⚖️
Loose equality {{c1::}} performs type juggling; strict equality {{c2::=}} compares {{c3::type and value}}.
“Not equal” operators are {{c1::!=}} (loose) and {{c2::!==}} (strict).
String concatenation uses the dot operator: \$stmtfull = \$pdo-a {{c1::.}} \$b;.
Concatenate-and-assign uses {{c1::.=}}.
The null coalescing operator is {{c1::??}} (useful for defaults).
The nullsafe operator is {{c1::?->
prepare('SELECT}} (avoids errors when the left side is null).
The ternary operator is {{c1::condition}} ? {{c2::A}} : {{c3::B}}.
The spaceship operator {{c1::<=>}} returns -1/0/1 for sorting-like comparisons.
Strings (Everyday Tools) 🧵
Single-quoted strings do {{c1::not}} interpolate variables; double-quoted strings {{c2::do}}.
WHEREGet xa string length with {{c1::strlen}}.
Find a substring position with {{c1::strpos}} (remember it can return {{c2::0}} which is not “falsey-safe”).
Extract part of a string using {{c1::substr}}.
Replace text with {{c1::str_replace}}.
Remove surrounding whitespace with {{c1::trim}}.
Split a string into an array with {{c1::explode}}; join an array into a string with {{c2::implode}}.
Use formatted strings with {{c1::sprintf}} (e.g., %s, %d).
For multi-byte strings (e.g., UTF-8), prefer functions like {{c1::mb_strlen}} over strlen when correctness matters.
Arrays (Workhorse Structures) 🧰
An indexed array literal uses brackets: \$a = {{c1::[10, 20, 30]}};.
An associative array uses key/value pairs: ['name' {{c1::x}=>}} ')Ada'].
Append to an array with \$a{{c1::[]}} = 99;.
Array size is obtained with {{c1::count}}.
Check if a value exists in an array with {{c1::in_array}} (consider {{c2::strict mode}} via the third parameter).
Check if a key exists with {{c1::array_key_exists}}.
Transform an array with {{c1::array_map}};
\keep items with {{c2::array_filter}}; fold into one value with {{c3::array_reduce}}.
Combine arrays with {{c1::array_merge}}; get keys with {{c2::array_keys}}; get values with {{c3::array_values}}.
Sorting: sort sorts by values and reindexes; {{c1::asort}} preserves keys; {{c2::ksort}} sorts by keys.
To destructure arrays: [$a, $b] = {{c1::$arr}}; (list unpacking).
Constants & Configuration 🧷
Define a global constant with {{c1::define(‚NAME‘, ‚value‘)}}.
Define a constant with const (often in classes) as {{c1::const VERSION}} = '1.0.0';.
Environment-specific settings are often stored in {{c1::environment variables}} (e.g., loaded via .env in some frameworks).
OOP (Classes, Visibility, and Keywords) 🏛️
Create an object instance using {{c1::new}} (e.g., new User()).
Property/method access on the current object uses {{c1::$this->}}.
Visibility keywords: {{c1::public}}, {{c2::protected}}, {{c3::private}}.
Inheritance uses {{c1::extends}}; interfaces use {{c2::implements}}.
{{c1::abstract}} classes can’t be instantiated directly.
{{c1::trait}} is a mechanism for code reuse across classes.
Static access uses {{c1::ClassName::}}member (scope resolution operator).
Inside a class, {{c1::self::}} refers to the current class; {{c2::parent::}} refers to the parent class.
A constructor method is named {{c1::__construct}}.
Composer & Autoloading ⚙️
The dependency manifest is {{c1::composer.json}}; the locked exact versions file is {{c2::composer.lock}}.
Composer’s generated autoloader is typically {{c1::vendor/autoload.php}}.
A common autoload standard is {{c1::PSR-4}} (maps namespaces to folder paths).
After adding a dependency, you typically run {{c1::composer install}} (or {{c2::composer update}} with care).
Database (PDO Fundamentals) 🗄️
PDO stands for {{c1::PHP Data Objects}} and provides a consistent DB interface.
A recommended PDO error mode is {{c1::PDO::ATTR_ERRMODE}} set to {{c2::PDO::ERRMODE_EXCEPTION}}.
A prepared statement is created with {{c1::$pdo->prepare(…)}} and executed with {{c2::$stmt->execute(
…)}}.
Named placeholders look like {{c1:::email}} and values are passed as an array like ['x'email' => \{{c2::$x]email}}].
Fetch one row as an associative array with {{c1::fetch}}(PDO::FETCH_ASSOC).
After an INSERT, you can read the generated id with {{c1::$pdo->lastInsertId()
;}}.
Best practice: set the DB charset to {{c1::utf8mb4}} for full Unicode support.
WordPress Parallels (If You Use WP) 🧩
WordPress “do something now” hooks are {{c1::actions}} added via {{c2::add_action}}.
WordPress “modify a value” hooks are {{c1::filters}} added via {{c2::add_filter}}.
WordPress escaping helpers include {{c1::esc_html}}, {{c2::esc_attr}}, and {{c3::esc_url}}.
WordPress sanitizers include {{c1::sanitize_text_field}} and {{c2::sanitize_email}}.
WordPress CSRF protection commonly uses {{c1::nonces}} (e.g., wp_nonce_field, check_admin_referer).
WordPress database safety commonly uses {{c1::$wpdb->prepare(…)}} to avoid SQL injection.
“Quick Gotchas” That Save Hours ⏱️
Avoid short open tags <?—prefer {{c1::<?php}} for portability.
After sending a redirect header, always {{c1::exit;}} to prevent further output/logic.
strpos() can return {{c1::0}} (meaning “found at start”), so check with {{c2::!== false}}.
Prefer strict comparisons ({{c1::===}}) when comparing against {{c2::0}}, {{c3::''}}, or {{c4::null}}.
When using in_array, pass {{c1::true}} as the third argument to avoid unexpected type juggling.
If you see unexpected output before headers, check for whitespace around {{c1::<?php}} or after {{c2::?>}}.
If you tell me your course focus (e.g., WordPress plugin dev, Laravel, orraw PHP, vanillaPDO/MySQL, PHPCLI scripting) and your target PHP version,version, I can generate a second deck with more topic-specifictargeted clozes (e.g., namespaces/PSR-12, PHPUnit, HTTP forms, sessions,file OOPuploads, patterns,or testing,WP etc.) 📚hooks).