Anki Cards: PHP Core Terminology
- In a web context, a single PHP execution that responds to one HTTP request is often called a {{c1::request}} (or a {{c2::script run}}).
- PHP is primarily an {{c1::interpreted}} language (executed by the {{c2::PHP engine}}).
- PHP is {{c1::server-side}}: the browser receives the {{c2::output}} (e.g., HTML/JSON), not your PHP {{c3::source code}}.
- PHP “{{c1::superglobals}}” are built-in variables available in any scope, e.g. {{c2::$GET}}, {{c3::$POST}}, {{c4::$_SERVER}}.
- “Type juggling” means PHP may {{c1::automatically convert}} values between types (e.g., string ↔ int) during {{c2::comparisons}} or operations.
- With
declare(strict_types=1);, scalar type hints become more {{c1::strict}} (fewer implicit {{c2::conversions}}). - Validation answers: {{c1::“Is this 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}}, often via Composer’s {{c2::PSR-4}} mapping.
- PDO is a database interface that supports {{c1::prepared statements}} to reduce {{c2::SQL injection}} risk.
Security Concepts (XSS / CSRF / SQLi)
- XSS often happens when you output untrusted data without proper {{c1::escaping}} in the correct {{c2::context}}.
- CSRF 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}}.
- In HTML context, a common safe-escape function is {{c1::htmlspecialchars}} with flags like {{c2::ENT_QUOTES}} and encoding {{c3::UTF-8}}.
- After sending a redirect header, you should usually call {{c1::exit}} to prevent further {{c2::output}}.
Language Constructs: Output & Debugging
echois a language construct used to {{c1::output}} text; it does {{c2::not return}} a value.printoutputs text and returns {{c1::1}} (so it can be used in {{c2::expressions}}).var_dump($x)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;includetypically emits a {{c2::warning}}.require_once/include_onceprevent 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 / elsechooses a branch based on a {{c1::boolean condition}}.switchcompares a single expression against multiple {{c1::cases}} and typically needs {{c2::break}} to avoid fall-through.matchis 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.breakexits the current {{c1::loop}} (or switch);continueskips to the {{c2::next iteration}}.foris good when you know the {{c1::index range}};whilecontinues 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 can 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 { ... }wherefinallyruns {{c1::even if an exception occurs}}. throw new Exception('msg');interrupts normal flow and transfers control to a matching {{c1::catch}} block.Throwableis 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}}.
nullrepresents an {{c1::absence of value}};isset($x)is false if$xis {{c2::null}} or undefined.- Two common ways to define constants:
define('X', 'y')and{{c1::const}} X = 'y';. constis evaluated at {{c1::compile time}} 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$maybeis {{c1::null}} or {{c2::unset}}. - Nullsafe operator:
\$user?->profile?->emailstops 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 compare with {{c2::=== false}} carefully).trim($s)removes whitespace from {{c1::both ends}};ltrimandrtrimremove 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 usein_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}}.
- Request metadata (method, headers info, path info) is in {{c1::$_SERVER}}.
- Uploaded file metadata is in {{c1::$_FILES}} (name/type/tmp_name/error/size).
- Sessions use {{c1::$_SESSION}}, but you must call {{c2::session_start()}} first.
- A safe read pattern:
\$q = \$_GET['q'] ?? '';uses a {{c1::default}} when the key is {{c2::missing}}. - 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 must be sent before any {{c1::output}} (even stray whitespace), otherwise you’ll get “{{c2::headers already sent}}”.
OOP Essentials (Classes, Visibility, Traits)
- Create an object with
new {{c1::ClassName}}()and access instance members with {{c2::$this->}}. - Visibility:
public(anywhere),protected(class + subclasses),private({{c1::class only}}). - Inheritance uses {{c1::extends}}; interfaces use {{c2::implements}}.
- An
abstractclass can’t be {{c1::instantiated}} and may contain abstract methods that must be {{c2::implemented}}. - A
traitallows horizontal code reuse viause {{c1::TraitName}};. - Static members belong to the {{c1::class}} (not the instance) and are accessed with
{{c2::ClassName::}}.
Composer (Modern PHP Workflow)
composer.jsondescribes dependencies and autoload rules;composer.lockpins {{c1::exact versions}}.- Install dependencies with
composer {{c1::install}}; update dependencies withcomposer {{c2::update}}. - PSR-4 autoloading maps a namespace prefix to a {{c1::directory}} (e.g.,
App\→{{c2::src/}}).
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()}} thenfetch()/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}} toexecute().
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 PHP files, it’s common to omit the closing tag
{{c1::?>}}to avoid accidental whitespace output. - In PHP, the string {{c1::'0'}} is falsy, so use {{c2::strict comparisons}} when it matters.
isset($x)is false when$xis {{c1::null}};empty($x)is true for values like'',0,'0',[], and {{c2::null}}.===compares both {{c1::type}} and value; use it especially when functions can return {{c2::false}} (e.g.,strpos).- Output buffering can delay output;
ob_start()begins buffering andob_end_flush(){{c1::sends}} the buffer. - Use
filter_var($email, FILTER_VALIDATE_EMAIL)to {{c1::validate}} an email (returns the value or {{c2::false}}). - Use
filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)to validate external input and avoid direct 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)(notrename).
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 (\$arr as {{c1::\$k}} => {{c2::\$v}}) { ... } - Minimal try/catch:
try { ... } catch ({{c1::Throwable}} \$e) { ... } - Minimal PDO select pattern:
\$stmt = \$pdo->prepare('SELECT ... WHERE x = {{c1:::x}}'); \$stmt->execute(['x' => \$x]);
If you tell me your course focus (e.g., WordPress plugin dev, Laravel, or vanilla PHP) and your target PHP version, I can generate a second deck with more topic-specific clozes (forms, sessions, OOP patterns, testing, etc.) 📚