Anki Cards: PHP Core Terminology
PHP Terminology (Core Concepts) 🧠
- A single execution of PHP code to respond to an HTTP request (or CLI run) is called a {{c1::script}} (or a {{c2::request}}).
- PHP is typically executed by an {{c1::interpreter}} (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 {{c3::PHP source}}.
- PHP can run in {{c1::web server mode}} (responding to HTTP) or in {{c2::CLI}} (command line).
- PHP’s execution model is usually {{c1::stateless per request}}; to persist data across requests you need {{c2::sessions}}, {{c3::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}}.
- Uploaded file metadata lives in {{c1::$_FILES}}.
- Cookie values are in {{c1::$COOKIE}}; server-side session data is in {{c2::$SESSION}} (after {{c3::session_start()}}).
- A 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?” is {{c1::validation}}; “make it cleaner/safer” is {{c2::sanitization}}; “make it safe to display” is {{c3::escaping}}.
- Preventing XSS primarily requires {{c1::escaping on output}} in the correct context (HTML, attribute, JS, URL).
- The go-to HTML escaping function is {{c1::htmlspecialchars}} with flags like {{c2::ENT_QUOTES}} and encoding {{c3::UTF-8}}.
- SQL Injection is prevented by using {{c1::prepared statements}} (e.g., via {{c2::PDO}}) instead of string concatenation.
- CSRF is mitigated using {{c1::anti-CSRF tokens}} (WordPress: {{c2::nonces}}).
- Passwords should be stored with {{c1::password_hash}} and checked with {{c2::password_verify}}—never with plain hashing like MD5.
- A secure mindset rule: never trust types from {{c1::$GET}}/{{c2::$POST}}; always {{c3::validate}} and {{c4::cast/allowlist}}.
PHP Output & Debugging 🧪
- The most common way to output text is {{c1::echo}} (a language construct).
printis similar to echo but it {{c1::returns}} {{c2::1}}.- For type + value debugging, use {{c1::var_dump($x)}}.
- For readable array/object output, use {{c1::print_r($x)}} (optionally with {{c2::true}} to return the string).
- To stop execution immediately, use {{c1::die()}} or {{c2::exit()}}.
- “Headers already sent” errors often occur because you produced {{c1::output}} (even whitespace) before calling {{c2::header()}}.
Includes & File Loading 📁
- If a file is missing, {{c1::require}} triggers a {{c2::fatal error}}, while {{c3::include}} only raises a warning and continues.
- To ensure a file is loaded at most once, use {{c1::require_once}} or {{c2::include_once}}.
- A best-practice for paths is using {{c1::DIR}} to build absolute-ish paths (e.g.,
require __DIR__ . '/vendor/autoload.php';). - In “pure PHP” files, it’s common to omit the closing tag {{c1::?>}} to prevent accidental whitespace output.
Control Flow (Conditionals & Loops) 🔁
- A standard conditional chain is {{c1::if}} → {{c2::elseif}} → {{c3::else}}.
switchrequires explicit {{c1::break}} to avoid {{c2::fall-through}}.match(PHP 8+) is an {{c1::expression}} that {{c2::returns a value}} and uses {{c3::strict comparison}}.- The most common loop for arrays is {{c1::foreach}}.
- To get both key and value in foreach:
foreach (\$arr as {{c1::\$k}} => {{c2::\$v}}) { ... }. breakexits 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
staticlocal 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 { ... }. - You can raise an exception with
{{c1::throw}} new Exception('message');. finallyruns 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:
\$full = \$a {{c1::.}} \$b;. - Concatenate-and-assign uses
{{c1::.=}}. - The null coalescing operator is {{c1::??}} (useful for defaults).
- The nullsafe operator is {{c1::?->}} (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}}.
- Get a 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
strlenwhen 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::=>}} '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:
sortsorts 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
.envin 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['email' => {{c2::$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, raw PHP, PDO/MySQL, CLI scripting) and your PHP version, I can generate a second deck with more targeted clozes (e.g., namespaces/PSR-12, PHPUnit, HTTP forms, file uploads, or WP hooks).