Skip to main content

Anki Cards: PHP Core Terminology

PHPCore Terminology (Core📌

Concepts) 🧠
  1. AIn web PHP, a single execution of PHP code to respond to an HTTP request (oris CLI run) isoften called a {{c1::script}request}} (or ascript {{c2::request}})run).
  2. PHP isruns typically executed byvia an {{c1::interpreter}} (the {{c2::PHP engine}})engine), not compiledby ahead-of-timeproducing a native binary like C/C++.
  3. PHP is a {{c1::server-side}} language:: the browser receives the {{c2::output}} (e.g., HTML/JSON), not yourthe {{c3::PHP source}}.
  4. PHPBuilt-in canarrays runthat inare always available (e.g., $_GET, $_POST, $_SERVER) are called {{c1::web server mode}superglobals}} (responding to HTTP) or in {{c2::CLI}} (command line).
  5. PHP’s executionautomatic modelconversion isbetween usuallytypes {{c1::stateless per request}}; to persist data across requests you need {{c2::sessions}}(e.g., {{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↔ int) is {{c1::$_GET}type juggling}}. Thedeclare(strict_types=1); superglobal for form-body parameters (common with POST forms) isenables {{c1::$_POST}strict typing}} behavior for {{c2::scalar type hints}}. RequestValidation metadata (method, headers info, paths, etc.) is found inasks: {{c1::$_SERVER}“Is this allowed?”}}; invalid input is typically {{c2::rejected}}. UploadedSanitization file metadata lives inasks: {{c1::$_FILES}“Can we make this safe/clean?”}. 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}transformed}}. PreventingEscaping XSS primarily requiresasks: {{c1::escaping“How ondo output}I safely output this in a context?”}} (HTML/attr/JS/URL), and is done at {{c2::output time}}. XSS happens when unescaped output lets an attacker run {{c1::JavaScript}} in the correctvictim’s context (HTML, attribute, JS, URL).browser. The go-to HTML escaping functionCSRF is a {{c1::htmlspecialchars}forged request}} withproblem; flagstypical likedefense is a per-request {{c2::ENT_QUOTES}} and encoding {{c3::UTF-8}token/nonce}}. SQL Injectioninjection is prevented by using {{c1::prepared statements}} (e.g.instead of unsafe string concatenation. require is {{c1::fatal}} if the file is missing; include emits a {{c2::warning}} and continues. Composer-style class loading is {{c1::autoloading}}, commonly via {{c2::PDO}PSR-4}}) instead of string concatenation.. CSRF is mitigated usingA {{c1::anti-CSRF tokens}namespace}} (WordPress:prevents naming collisions by qualifying names like MyApp\Foo. {{c1::Dependency injection}} means {{c2::nonces}passing dependencies in}}) rather than creating them inside the class/function. {{c1::PDO}} is PHP’s standard DB interface and supports {{c2::prepared statements}}. PasswordsIn shouldWordPress, bea storedhook withis a {{c1::password_hash}callback point}}: and checked withan {{c2::password_verify}action}}—never with“does plainsomething,” hashing like MD5. A secure mindset rule: never trust types from {{c1::$GET}}/{{c2::$POST}}; alwaysa {{c3::validate}filter}} and“modifies {{c4::cast/allowlist}}.a value.”

      Daily PHP OutputConstructs &(“Commands”) Debugging🧠

      🧪
      1. Theecho most common way to output text isoutputs {{c1::echo}strings}} (aand languagecan construct)output multiple args separated by commas).
      2. print is similar tolike echo but itreturns {{c1::returns}1}} (so it’s usable in expressions).
      var_dump($x) shows both {{c1::type}} and {{c2::1}value}} (great for debugging). Forprint_r($x, typetrue) +returns valuethe debugging,output useas a {{c1::var_dump($x)}}. For readable array/object output, use {{c1::print_r($x)}string}} (optionallywhen withthe second argument is {{c2::true}} to return the string). Todie() stop/ execution immediately, useexit() {{c1::die()}stops execution}} orimmediately {{c2::exit()}}(often after a redirect). “Headersinclude_once 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. Torequire_once ensure a file is loadedincluded at most once, use {{c1::require_once}once}} orper {{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.request.

        Control Flow (ConditionalsIf &/ Switch / Match / Loops) 🔁


        1. Aif standard(...) conditional{} chainruns only when the condition is {{c1::if}} → {{c2::elseif}} → {{c3::else}true}}.
        2. switch requirestypically explicitneeds {{c1::break}} to avoid {{c2::fall-through}}.through into the next case.
        3. match (PHP...) 8+){ ... } is an {{c1::expression}} that {{c2::returns a value}} and(unlike switch).
        match uses {{c3:c1::strict comparison}comparisons}} (no type juggling like loose switch cases can do). foreach ($arr as $value) iterates over the array’s {{c1::values}}. Theforeach most($arr commonas loop$k for=> arrays$v) isgives both the {{c1::foreach}key}}. To get both key and value in foreach: foreach (\$arr as {{c1::\$k}} =>the {{c2::\$v}value}}) { ... }. break exits a loop;the {{c1::continue}current loop/switch}}; continue skips to the {{c2::next iteration.iteration}}. A do { ... } while (...); loop runs the body at least {{c1::once}}.

        Functions & ScopeOrganization 🧩


        1. A function can declaredefine a default parameter like function f($x = 123), meaning it’s {{c1::optional}} when calling.
        return exits a function and optionally provides a {{c1::value}}. global $x; accesses a variable from the {{c1::global scope}} (best used {{c2::sparingly}}). static $x = 0; inside a function persists {{c1::between calls}} during the same request. A function with a return type using: functionint f():promises it will return an {{c1::int}} { ... }. Function parameters can have defaults like function f(\$x = {{c1::123}}). Variables inside a function are local unless declared {{c1::global}integer}} (useor sparingly). A static local variable in a function {{c1::persists between calls}}throw). In modern PHP, functions can be {{c1::passed as callables}} (e.g., to array_map). Anonymous functions use function() {}; arrow functions use {{c1::fn}strict_types}}(\$x) => ... (shortwhen syntax).you want stricter scalar parameter/return behavior.

        ErrorsError Handling & Exceptions 🚨🚧


        1. Exception handling uses try { ... } catch ({{c1::Throwable}}Throwable \$e) { ... } catches both {{c1::Exception}} and many {{c2::Error}} types.
        finally { ... }. You can raise an exception with {{c1::throw}} new Exception('message');. finally runs whether an exception iswas thrown{{c1::thrown}} or not:not it’s(good idealfor cleanup). throw new Exception('msg'); {{c1::raises}} an exception to be handled by a caller. If an exception is not caught, it typically causes a {{c1::fatal error}} and aborts the request.

        OOP: Classes, Visibility, Inheritance 🧱


          new ClassName() creates an {{c1::object instance}}. public members are accessible {{c1::everywhere}}; protected inside {{c2::class + subclasses}}; private only inside the {{c3::declaring class}}. extends means {{c1::inheritance}}; implements means fulfilling an {{c2::interface contract}}. $this-> accesses the {{c1::current object}} instance members. self:: refers to the {{c1::current class}}; parent:: refers to the {{c2::parent class}}. A trait is a mechanism for {{c1::cleanup}code reuse}} across classes (without inheritance). InAn production,abstract youclass generallycannot be {{c1::log errors}instantiated}} ratherdirectly. thanAn displayinginterface themdefines to{{c1::method users.signatures}} that implementing classes must provide.

          Variables, Types, and “Type Juggling”Operators 🧱


          1. PHP variables start with the symbola {{c1::$}}. sign.
          2. PHPdefine('APP_ENV', supports'dev') “typedefines juggling,” meaning it maya {{c1::auto-convert}constant}} typesat runtime; const defines a constant at {{c2::compile time}} (stringand can int,be etc.)used in classes).
          3. ToScalar enforce stricter scalar type checking, add {{c1::declare(strict_types=1);}} at the top of a file.
          Common scalar types aretypes: {{c1::int}}, {{c2::float}}, {{c3::string}}, {{c4::bool}}. Thenull specialrepresents typean representing{{c1::absence}} “noof value”value. . is {{c1::null}string concatenation}}. in PHP. To.= castperforms toconcatenation integer, use {{c1::(int)}}\$x; to cast to string, use {{c2::(string)}}\$x. A notorious truthiness gotcha: the stringand {{c1::'0'assignment}} in one step. == is {{c1::loose comparison}} (type juggling); === 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::!=}strict}} (loose)type and+ {{c2::!==}} (strict). String concatenation uses the dot operator: \$full = \$a {{c1::.}} \$b;. Concatenate-and-assign uses {{c1::.=}}value). The null“spaceship” operator <=> returns {{c1::-1}}, {{c2::0}}, or {{c3::1}} for ordering comparisons. Null coalescing operator?? uses the right-hand side only if the left is {{c1::??null or undefined}}} (useful for defaults). TheNullsafe nullsafe?-> operatorstops isand returns {{c1::?->}null}} (avoids errors whenif the left side is null){{c2::null}}. && / || are {{c1::short-circuit}} boolean operators. The ternary operatorcond is? a : b picks {{c1::condition}a}} ?when cond is true, else {{c2::A}b}} : {{c3::B}}. The spaceship operator {{c1::<=>}} returns -1/0/1 for sorting-like comparisons.

            Strings (Everyday Tools) 🧵


            1. Single-quotedIn stringssingle doquotes '...', variables are generally {{c1::not}not interpolated}}.
            In double quotes "...", variables like $name are {{c1::interpolated}}. strlen($s) returns the string length in {{c1::bytes}} interpolate(multibyte variables;text double-quotedmay stringsneed {{c2::do}mb_strlen}}). Getstrpos($haystack, a$needle) stringreturns lengththe withposition or {{c1::strlen}false}} (so use === false checks). Findtrim($s) aremoves substringwhitespace positionfrom withthe {{c1::strpos}start and end}} (remember it can return {{c2::0}} which is not “falsey-safe”). Extract part of a string using {{c1::substr}}.string. Replaceexplode(',', text$s) with {{c1::str_replace}}. Remove surrounding whitespace with {{c1::trim}}. Splitconverts a string into an array with {{c1::explode}array}};. joinimplode(',', $arr) converts an array into a string with {{c2:c1::implode}string}}. Usesprintf("Hi %s", $name) returns a formatted strings with {{c1::sprintf}string}} (e.g.,without %s,echoing %d). For multi-byte strings (e.g., UTF-8), prefer functions like {{c1::mb_strlen}} over strlen when correctness matters.it.

            Arrays (Workhorse Structures)Workhorse) 🧰


            1. An[] creates an {{c1::array}} literal (indexed or associative).
            Indexed array literal uses brackets:example: \$a = {{c1::[10, 20, 30]}}; uses numeric {{c1::indexes}}. An associativeAssociative array uses key/value pairs:example: ['name' {{c1::=>}} 'Ada'] uses string {{c1::keys}}. Append$a[] = 99; appends to the {{c1::end}} of an indexed array. count($arr) returns the number of {{c1::elements}}. in_array($needle, $haystack, true) uses strict checking when the third argument is {{c1::true}}. array_key_exists('k', $arr) checks for the presence of a {{c1::key}} even if its value is {{c2::null}}. array_map(fn($x) => ..., $arr) transforms each element and returns a {{c1::new array}}. array_filter($arr, $fn) keeps elements where the callback returns {{c1::true}}. array_reduce($arr, $fn, $initial) folds an array withinto \$a{{c1::[]}}a = 99;. Array size is obtained withsingle {{c1::count}value}}. Checksort($arr) ifsorts avalues value exists in an array withand {{c1::in_array}reindexes}} (considernumeric {{c2::strict mode}} via the third parameter).keys. 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: sortasort($arr) sorts by valuesvalue andwhile reindexes; {{c1::asort}preserving keys}}. preserves keys; {{c2::ksort}}ksort($arr) sorts by keys. To destructure arrays: [$a, $b] = {{c1::$arr}key}}; (list unpacking).

            ConstantsHTTP & ConfigurationSuperglobals 🧷🌐


            1. DefineQuery astring globalparameters constantare withread from {{c1::define(‚NAME‘,$_GET}}.
            ‚value‘Form body parameters are commonly read from {{c1::$_POST}}. Request metadata (method, headers info, URI) is found in {{c1::$_SERVER}}. Uploaded file info is in {{c1::$_FILES}} (name/type/tmp_name/error/size). Session data uses {{c1::$_SESSION}} after calling {{c2::session_start()}}. DefineA asafe constantread withpattern: const (often in classes) as {{c1::const VERSION}}$q = $_GET['1.0.0'q'] ?? '';. Environment-specificavoids settings are often stored inan {{c1::environmentundefined variables}index}} (e.g.,notice. loadedheader('Location: via .env/path'); intriggers somean frameworks)HTTP {{c1::redirect}}. After sending a Location header, you should call {{c1::exit}} to stop further output. http_response_code(404); sets the HTTP status code to {{c1::404}}.

            OOPSecurity (Classes,Defaults Visibility, and Keywords) 🏛🛡


            1. CreateFor anHTML objectoutput, instancehtmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') prevents {{c1::XSS}} in HTML/text contexts.
            ENT_QUOTES escapes both {{c1::single}} and {{c2::double}} quotes. Passwords should be stored using {{c1::new}password_hash}} (not md5/sha1). Verify a password with {{c1::password_verify($pw, $hash)}}. SQL safety best practice: use {{c1::prepared statements}} with bound parameters (not string concatenation). CSRF defense: include a per-request {{c1::token}} and verify it on submission. Never trust $_GET/$_POST types: always {{c1::validate}} and/or {{c2::cast}} (e.g., new User()(int)). Property/methodOutput accessescaping on the current object usesis {{c1::$this->context-dependent}}}. 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 (scopeHTML resolutionvs operator).attribute Insidevs aURL class,vs {{c1::self::}} refers to the current class; {{c2::parent::}} refers to the parent class. A constructor method is named {{c1::__construct}}JS).

            Composer & Autoloading ⚙️


            1. Thecomposer.json dependencydeclares manifestdependencies isand {{c1::autoload rules}}.
            composer.json}};lock pins the locked {{c1::exact versionsversions}} file is {{c2::composer.lock}}.installed. Composer’s generatedautoloader autoloaderentry file is typically {{c1::vendor/autoload.php}}. AIn commoncode, autoloadrequire standard__DIR__ is. '/vendor/autoload.php'; enables {{c1::PSR-4}autoloading}} (maps namespaces to folder paths). AfterPSR-4 adding a dependency, you typically runmaps {{c1::composer install}namespaces}} (orto {{c2::composerdirectory update}paths}} with care).

            DatabasePDO (PDO Fundamentals)Database) 🗄️


            1. PDOIn standsPDO, forsetting PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION makes DB errors throw {{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}exceptions}}. A prepared statement is created with $pdo->{{c1::$pdo->prepare(…prepare}}(...)}} and executed with {{c2::$stmt->execute(…)}}. NamedParameters placeholdersare lookprovided likevia $stmt->{{c1:::email}execute}} and values are passed as an array like (['email' => {{c2::$email}}]email]) (named placeholders). FetchFetching one row as an associative array can be done with $stmt->fetch(PDO::{{c1::fetch}FETCH_ASSOC}}(PDO::FETCH_ASSOC)). After an INSERT, you can read the generated id with $pdo->{{c1::$pdo->lastInsertId(lastInsertId}}()}}. Best practice: setgets the DBlast charsetgenerated toID {{c1::utf8mb4}} for full Unicode support.(driver-dependent).

            WordPress Parallels (If You Use WP) 🧩


            1. WordPress “do something now” hooksactions are registered with {{c1::actions}} added via {{c2::add_action}}.
            ; WordPressfilters “modify a value” hooks are {{c1::filters}} added viawith {{c2::add_filter}}. WordPressA escapingfilter helperscallback includemust {{c1::esc_html}return}}, the modified value; an action callback typically {{c2::esc_attr}does not}}. WordPress escaping helpers: esc_html, andesc_attr, {{c3:c1::esc_url}}. for URLs. WordPress sanitizers include {{c1::sanitize_text_field}}sanitize_text_field and {{c2:c1::sanitize_email}}. WordPress CSRF protection commonly uses {{c1::nonces}} (e.g., wp_nonce_field, check_admin_referer). $wpdb->prepare(...) is the WordPress databasepattern safety commonly usesfor {{c1::$wpdb->prepare(…)safe SQL}}} to avoid SQL injection..

            QuickI Gotchas”Forget ThatThis” SaveReminders Hours ⏱🗂


            1. AvoidPrefer shortthe openfull tagsopening <?—prefertag {{c1::<?php}} for(avoid portability.short tags).
            2. AfterIn sendingpure aPHP redirectfiles, header,it’s alwayscommon to omit the closing tag ?> to avoid accidental {{c1::exit;whitespace output}}.
            In PHP, the string '0' is {{c1::falsy}} to(so preventstrict furthercomparisons output/logic.can matter). HTTP headers must be sent before any {{c1::output}} (even whitespace), otherwise you get “headers already sent.”

            Extra High-Value Additions (Fits the Topic) ✨


              error_reporting(E_ALL); and ini_set('display_errors', '1'); are useful in {{c1::development}} (but not in production). Prefer filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS) for simple input handling, but still {{c1::validate}} properly. json_encode($data, JSON_UNESCAPED_UNICODE) produces {{c1::JSON}} output; set header Content-Type: application/json. To read JSON request bodies: $raw = file_get_contents('php://input'); $data = json_decode($raw, true);true yields an {{c1::associative array}}. isset($x) is false if $x is {{c1::not set}} or {{c2::null}}. empty($x) treats values like 0, '0', [], and null as {{c1::empty}} (be careful). Use === when checking strpos(...) canresults returnbecause position {{c1::0}} (meaningis “founda atvalid start”),match sobut checkis with {{c2::!==falsy}}. false}The directory constant __DIR__ gives the current file’s {{c1::directory path}} (safer than relative paths). require vs require_once: require_once adds overhead; prefer {{c1::autoloading}} for classes instead of many *_once. PreferUse strictpassword_hash comparisonswith (PASSWORD_DEFAULT so the algorithm can {{c1::===}})upgrade whenover comparing against {{c2::0}}, {{c3::''}}, or {{c4::null}time}}. WhenIn usingprepared in_array,statements, passnever interpolate variables directly into SQL; bind them as {{c1::true}parameters}} as the third argument to avoid unexpected type juggling.. IfIn youPHP see unexpected output before headers, check for whitespace around8+, match has no fall-through and will throw UnhandledMatchError if no case matches and there’s no {{c1::<?php}default}}. For arrays, === orcompares afterboth order and types; for “same key/value pairs regardless of order,” use {{c1::ksort}} first. In OOP, prefer constructor injection: __construct(private Logger $logger) is promoted property syntax (PHP {{c2:c1::?>8.0+}}). For safe redirects, validate destination URLs to prevent {{c1::open redirect}} vulnerabilities.

              If you tell me yourwhether courseyou’re focususing (e.g.PHP 7.4, 8.0–8.4, and whether you’re focusing on WordPress pluginplugin/theme dev, or Laravel,general raw PHP, PDO/MySQL, CLI scripting) and your PHP versionbackend, I can generate a second deck with more targetedscenario-based clozes (e.g., namespaces/PSR-12, PHPUnit, HTTPdebugging, forms, fileauth, uploads,PDO orpitfalls) WP hooks).🧠✅