Skip to main content

Anki Cards: PHP Core Terminology

  1. 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}}).
  2. PHP is primarily an {{c1::interpreted}} language (executed by the {{c2::PHP engine}}).
  3. PHP is {{c1::server-side}}: the browser receives the {{c2::output}} (e.g., HTML/JSON), not your PHP {{c3::source code}}.
  4. PHP “{{c1::superglobals}}” are built-in variables available in any scope, e.g. {{c2::$GET}}, {{c3::$POST}}, {{c4::$_SERVER}}.
  5. “Type juggling” means PHP may {{c1::automatically convert}} values between types (e.g., string ↔ int) during {{c2::comparisons}} or operations.
  6. With declare(strict_types=1);, scalar type hints become more {{c1::strict}} (fewer implicit {{c2::conversions}}).
  7. Validation answers: {{c1::“Is this allowed?”}} ✅ (reject invalid), while sanitization answers: {{c2::“Can we clean/transform it?”}} 🧼.
  8. Escaping means making output safe for a specific {{c1::context}} (HTML/attribute/URL/JS), typically done {{c2::right before output}}.
  9. A {{c1::namespace}} helps prevent {{c2::naming collisions}} by qualifying identifiers like MyApp\Tools\Mailer.
  10. “Dependency injection (DI)” means you {{c1::pass dependencies in}} (e.g., via constructor) instead of {{c2::creating them inside}}.
  11. An “autoload” mechanism loads class files when a class is {{c1::referenced}}, often via Composer’s {{c2::PSR-4}} mapping.
  12. PDO is a database interface that supports {{c1::prepared statements}} to reduce {{c2::SQL injection}} risk.

Security Concepts (XSS / CSRF / SQLi)

  1. XSS often happens when you output untrusted data without proper {{c1::escaping}} in the correct {{c2::context}}.
  2. CSRF is a forged request from another site; mitigation usually requires a per-request {{c1::token}} (WordPress: {{c2::nonce}}).
  3. SQL injection risk increases when you build queries via string {{c1::concatenation}}; safer: {{c2::prepared statements}} with bound parameters.
  4. A secure default: {{c1::validate input}}, then {{c2::sanitize if needed}}, and finally {{c3::escape on output}} 🛡️.
  5. Passwords should be stored using {{c1::password_hash}} (not plain text, not fast hashes like {{c2::MD5}}).
  6. To check a password, use {{c1::password_verify}} against the stored {{c2::hash}}.
  7. In HTML context, a common safe-escape function is {{c1::htmlspecialchars}} with flags like {{c2::ENT_QUOTES}} and encoding {{c3::UTF-8}}.
  8. After sending a redirect header, you should usually call {{c1::exit}} to prevent further {{c2::output}}.

Language Constructs: Output & Debugging

  1. echo is a language construct used to {{c1::output}} text; it does {{c2::not return}} a value.
  2. print outputs text and returns {{c1::1}} (so it can be used in {{c2::expressions}}).
  3. var_dump($x) shows both {{c1::type}} and {{c2::value}} (great for debugging).
  4. print_r($x, true) returns a {{c1::string}} representation instead of {{c2::printing}} it.
  5. die() is an alias of {{c1::exit()}} and stops script {{c2::execution}} immediately.

Including Files & Autoloading

  1. require 'file.php'; causes a {{c1::fatal error}} if the file is missing; include typically emits a {{c2::warning}}.
  2. require_once / include_once prevent loading the same file {{c1::more than once}} in a single {{c2::request}}.
  3. A common Composer autoload entrypoint is require {{c1::__DIR__}} . {{c2::'/vendor/autoload.php'}}; ⚙️

Control Flow (Conditionals, match, Loops)

  1. if / elseif / else chooses a branch based on a {{c1::boolean condition}}.
  2. switch compares a single expression against multiple {{c1::cases}} and typically needs {{c2::break}} to avoid fall-through.
  3. match is an expression that {{c1::returns a value}} and uses {{c2::strict comparison}} semantics.
  4. foreach ($arr as $value) iterates over {{c1::values}}; foreach ($arr as $k => $v) gives both {{c2::keys}} and values.
  5. break exits the current {{c1::loop}} (or switch); continue skips to the {{c2::next iteration}}.
  6. for is good when you know the {{c1::index range}}; while continues as long as a {{c2::condition}} is true.

Functions & Scope

  1. A function definition looks like function name($a, $b = 123): int { {{c1::return}} ... }.
  2. A parameter with = ... is a {{c1::default argument}}, used when the caller omits that {{c2::parameter}}.
  3. Variables declared inside a function are {{c1::local}} by default (not visible {{c2::outside}}).
  4. global $x; pulls a variable from the {{c1::global scope}} into the function (use {{c2::sparingly}}).
  5. A static $count = 0; inside a function persists its value between {{c1::calls}} within the same {{c2::request}}.
  6. Anonymous functions are created with function (...) { ... } and can be stored in a {{c1::variable}} as a {{c2::callable}}.
  7. To import outer variables into a closure, use function () use ($x) { ... } (captures by {{c1::value}} by default).

Error Handling (Exceptions)

  1. Exception flow: try { ... } catch (Throwable $e) { ... } finally { ... } where finally runs {{c1::even if an exception occurs}}.
  2. throw new Exception('msg'); interrupts normal flow and transfers control to a matching {{c1::catch}} block.
  3. Throwable is the interface implemented by both {{c1::Exception}} and {{c2::Error}} types.

Variables, Types, Constants

  1. PHP variables start with {{c1::$}} (e.g., \$name = 'Ada';).
  2. Common scalar types: {{c1::int}}, {{c2::float}}, {{c3::string}}, {{c4::bool}}.
  3. null represents an {{c1::absence of value}}; isset($x) is false if $x is {{c2::null}} or undefined.
  4. Two common ways to define constants: define('X', 'y') and {{c1::const}} X = 'y';.
  5. const is evaluated at {{c1::compile time}} and is often used in {{c2::classes}}.

Operators (Daily Drivers)

  1. String concatenation uses . and concatenation assignment uses {{c1::.=}}.
  2. “Loose” comparisons use {{c1::==}} (type juggling); “strict” comparisons use {{c2::===}} (type + value).
  3. The spaceship operator <=> returns {{c1::-1}}, {{c2::0}}, or {{c3::1}} depending on ordering.
  4. Null coalescing: \$x = \$maybe ?? 'default'; uses 'default' if $maybe is {{c1::null}} or {{c2::unset}}.
  5. Nullsafe operator: \$user?->profile?->email stops and yields {{c1::null}} if an intermediate is {{c2::null}}.
  6. Ternary operator: \$label = \$ok ? 'Yes' : 'No'; chooses between {{c1::two values}} based on a {{c2::condition}}.

Strings (Quoting, Interpolation, Utilities)

  1. In single quotes 'Hello \$name', variables are {{c1::not interpolated}}.
  2. In double quotes "Hello \$name", variables are {{c1::interpolated}} (replaced with their {{c2::values}}).
  3. strlen($s) returns the string’s {{c1::length}} (bytes; for multibyte use {{c2::mb_strlen}}).
  4. strpos($haystack, $needle) returns the position or {{c1::false}} (so compare with {{c2::=== false}} carefully).
  5. trim($s) removes whitespace from {{c1::both ends}}; ltrim and rtrim remove from {{c2::one side}}.
  6. explode(',', $s) converts string → {{c1::array}}; implode(',', $arr) converts array → {{c2::string}}.
  7. sprintf('Hi %s, you have %d', $name, $count) formats text with {{c1::placeholders}}.

Arrays (Creation, Access, Common Tools)

  1. Indexed arrays look like \$a = [10, 20, 30]; while associative arrays look like \$u = ['name' => 'Ada']; (keys are {{c1::strings}}).
  2. Append to an array with \$a[] = 99; (auto-increments the {{c1::next index}}).
  3. count($arr) returns the number of {{c1::elements}}.
  4. in_array($needle, $haystack) checks for a value; for strict checking use in_array(..., ..., {{c1::true}}).
  5. array_key_exists('k', $arr) checks if a {{c1::key exists}} (even if value is {{c2::null}}).
  6. array_map($fn, $arr) transforms each element into a new {{c1::array}}.
  7. array_filter($arr, $fn) keeps elements where the callback returns {{c1::true}}.
  8. array_reduce($arr, $fn, $initial) folds the array into a single {{c1::value}}.
  9. array_merge($a, $b) combines arrays; numeric keys are {{c1::reindexed}} by default.
  10. Sorting: sort($arr) sorts values and reindexes; asort($arr) preserves {{c1::keys}}.

HTTP & Superglobals

  1. Query-string parameters are in {{c1::$GET}}, form body fields are in {{c2::$POST}}.
  2. Request metadata (method, headers info, path info) is in {{c1::$_SERVER}}.
  3. Uploaded file metadata is in {{c1::$_FILES}} (name/type/tmp_name/error/size).
  4. Sessions use {{c1::$_SESSION}}, but you must call {{c2::session_start()}} first.
  5. A safe read pattern: \$q = \$_GET['q'] ?? ''; uses a {{c1::default}} when the key is {{c2::missing}}.
  6. Redirects are sent with header('Location: /path'); and should be followed by {{c1::exit}}.
  7. Set an HTTP status with http_response_code({{c1::404}}); (or other codes).
  8. Headers must be sent before any {{c1::output}} (even stray whitespace), otherwise you’ll get “{{c2::headers already sent}}”.

OOP Essentials (Classes, Visibility, Traits)

  1. Create an object with new {{c1::ClassName}}() and access instance members with {{c2::$this->}}.
  2. Visibility: public (anywhere), protected (class + subclasses), private ({{c1::class only}}).
  3. Inheritance uses {{c1::extends}}; interfaces use {{c2::implements}}.
  4. An abstract class can’t be {{c1::instantiated}} and may contain abstract methods that must be {{c2::implemented}}.
  5. A trait allows horizontal code reuse via use {{c1::TraitName}};.
  6. Static members belong to the {{c1::class}} (not the instance) and are accessed with {{c2::ClassName::}}.

Composer (Modern PHP Workflow)

  1. composer.json describes dependencies and autoload rules; composer.lock pins {{c1::exact versions}}.
  2. Install dependencies with composer {{c1::install}}; update dependencies with composer {{c2::update}}.
  3. PSR-4 autoloading maps a namespace prefix to a {{c1::directory}} (e.g., App\{{c2::src/}}).

PDO Database Snippets (Practical)

  1. A PDO DSN for MySQL often includes charset={{c1::utf8mb4}} to support full Unicode.
  2. Enable exceptions for PDO with PDO::ATTR_ERRMODE => PDO::ERRMODE_{{c1::EXCEPTION}}.
  3. Prepared statement flow: prepare() then {{c1::execute()}} then fetch()/fetchAll().
  4. fetch(PDO::FETCH_ASSOC) returns one row as an associative {{c1::array}}.
  5. lastInsertId() returns the last generated {{c1::AUTO_INCREMENT}} value for the current connection.
  6. Parameter binding uses placeholders like :email, and values are provided as an {{c1::array}} to execute().

WordPress Parallels (If You Use WP)

  1. WordPress “actions” run code at a hook point via {{c1::add_action}}; “filters” modify a value via {{c2::add_filter}}.
  2. Common WP escaping helpers: esc_html(), esc_attr(), and {{c1::esc_url()}}.
  3. Common WP sanitizers: sanitize_text_field() and {{c1::sanitize_email()}}.
  4. WP nonces help mitigate {{c1::CSRF}} via functions like wp_nonce_field() and {{c2::check_admin_referer()}}.
  5. WP database safety uses \$wpdb->{{c1::prepare}}(...) to safely insert variables into queries.

Common Gotchas & “Sticky” Reminders

  1. Prefer the full opening tag {{c1::<?php}} over short tags <? for portability.
  2. In pure PHP files, it’s common to omit the closing tag {{c1::?>}} to avoid accidental whitespace output.
  3. In PHP, the string {{c1::'0'}} is falsy, so use {{c2::strict comparisons}} when it matters.
  4. isset($x) is false when $x is {{c1::null}}; empty($x) is true for values like '', 0, '0', [], and {{c2::null}}.
  5. === compares both {{c1::type}} and value; use it especially when functions can return {{c2::false}} (e.g., strpos).
  6. Output buffering can delay output; ob_start() begins buffering and ob_end_flush() {{c1::sends}} the buffer.
  7. Use filter_var($email, FILTER_VALIDATE_EMAIL) to {{c1::validate}} an email (returns the value or {{c2::false}}).
  8. Use filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) to validate external input and avoid direct use of {{c1::superglobals}} (optional style).
  9. When handling file uploads, always check \$_FILES['x']['error'] === {{c1::UPLOAD_ERR_OK}} before moving the file.
  10. Move an uploaded file safely with {{c1::move_uploaded_file}}($tmp, $destination) (not rename).

Bonus: Mini “Code Shape” Clozes (Fast Recall)

  1. Minimal safe redirect pattern: header('Location: /x'); {{c1::exit;}}
  2. Minimal HTML escaping pattern: echo htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, '{{c1::UTF-8}}');
  3. Minimal null default pattern: \$name = \$_GET['name'] {{c1::??}} 'Guest';
  4. Minimal foreach with key/value: foreach (\$arr as {{c1::\$k}} => {{c2::\$v}}) { ... }
  5. Minimal try/catch: try { ... } catch ({{c1::Throwable}} \$e) { ... }
  6. 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.) 📚