Programming with PHP | Semester 4 Core Notes
Semester 4 - Page 4: Programming with PHP. 29 numbered topics, highlighted rules, worked examples, answered exam questions, architecture diagrams, security tables and five complete PHP CLI programs. General common-core preparation, not an official syllabus or production security certification. Examples tested on PHP 8.1.2 CLI; use a currently supported runtime and check your assigned version.
demo.php, check syntax with php -l demo.php, then run php demo.php. The five demos need no database, web server or packages. They use synthetic data and do not write files or make network requests. Form input is simulated, not an HTTP endpoint. The Event object is in-memory and not persistent/concurrency-safe. Password output is boolean, never a reusable credential. Server/database/session/upload sections explain architecture, not a fully tested application.Topic map
- Server-side request-response flow
- Syntax, variables and constants
- Types and deliberate conversion
- Operators, equality and control flow
- Functions, arguments and return types
- Strings, interpolation and encoding
- Arrays, keys and foreach
- Includes, namespaces and dependencies
- Classes, encapsulation and invariants
- Inheritance, interfaces, traits and exceptions
- Forms, superglobals and validation
- Output escaping and XSS
- GET, POST, status codes and redirects
- Cookies and session lifecycle
- Session fixation and authentication state
- CSRF and authorization
- Database connections and PDO
- Prepared statements and bound values
- Transactions, constraints and concurrency
- Password storage and verification
- Files, paths and cleanup
- Uploads and content checks
- Dates, timezones and server configuration
- Regular expressions and parsing limits
- JSON and APIs
- MVC, templates and routing
- Testing, logging and dependency care
- Worked RSVP architecture
- Revision and exam answer structure
1. Server-side request-response flow
PHP executes on the server and sends a response, often HTML or JSON. The browser receives the output, not the PHP source, when the server is correctly configured; static file exposure is a deployment risk.
Answer: No. PHP needs a configured interpreter/server; JavaScript and PHP execute in different environments.
Browser request
-> web server + PHP
-> domain / database work
-> HTTP response to browser2. Syntax, variables and constants
PHP code starts with an opening PHP tag; variables begin with a dollar sign and names are case-sensitive. Statements generally end with semicolons. Use constants for values that should not change.
Answer: HTTP headers must be sent before body output, so whitespace or debugging text can prevent later header changes.
3. Types and deliberate conversion
PHP has booleans, integers, floats, strings, arrays, objects, null and other types. Numeric conversions and strict type declarations have specific rules; use explicit validation for untrusted request data.
Answer: No. It affects scalar type coercion for calls from that file, not domain validity or HTTP input shape.
4. Operators, equality and control flow
=== compares type and value; == permits type juggling. Use if, loops and match/switch with version-aware semantics; short-circuit expressions can prevent invalid operations.
Answer: No. Number-to-nonnumeric-string comparisons changed; do not rely on old surprising coercions.
5. Functions, arguments and return types
Functions make validation and domain rules reusable. Parameters and return declarations document a contract; exceptions can report invalid domain inputs. Keep side effects separate from pure calculation.
Answer: They straddle the pass boundary and expose off-by-one conditions.
Strict comparison, arrays and functions
<?php
declare(strict_types=1);
function grade(int $mark): string {
if ($mark < 0 || $mark > 100) {
throw new InvalidArgumentException('mark outside 0..100');
}
return $mark >= 40 ? 'PASS' : 'FAIL';
}
var_dump(0 == '0', 0 === '0');
$marks = [39, 40, 100];
foreach ($marks as $mark) {
echo $mark, ': ', grade($mark), PHP_EOL;
}
try { grade(101); }
catch (InvalidArgumentException $e) { echo "invalid mark", PHP_EOL; }
Checked output:
bool(true) bool(false) 39: FAIL 40: PASS 100: PASS invalid mark
6. Strings, interpolation and encoding
Single-quoted and double-quoted strings have different interpolation/escape behavior. PHP strings are byte sequences; text encoding must be agreed explicitly, usually UTF-8 for web output.
Answer: No. Validate or handle invalid sequences and match encoding across storage, output and transport.
7. Arrays, keys and foreach
PHP arrays are ordered maps supporting integer and string keys. foreach can iterate keys and values; sorting functions differ in whether they preserve keys. Be careful with lingering references after by-reference loops.
Answer: It can remain a reference to the last element and accidentally modify that element later.
8. Includes, namespaces and dependencies
include and require load PHP files; require failures stop normal execution. Use fixed trusted paths, namespaces and controlled autoloading. Composer manages dependencies and its lock file pins resolved versions.
Answer: It can permit local or remote file inclusion and unintended code execution.
9. Classes, encapsulation and invariants
Classes group state and behavior; visibility restricts access. Constructors should establish invariants, and methods must preserve them. Typed properties need initialization before reading.
Answer: No. It is a single-process teaching model with no persistence, identity proof or concurrency control.
Encapsulated capacity with duplicate handling
<?php
declare(strict_types=1);
final class Event {
private array $registered = [];
public function __construct(private int $capacity) {
if ($capacity < 0) { throw new InvalidArgumentException('negative capacity'); }
}
public function register(int $student): string {
if ($student <= 0) { throw new InvalidArgumentException('invalid student'); }
if (isset($this->registered[$student])) { return 'duplicate'; }
if (count($this->registered) >= $this->capacity) { return 'full'; }
$this->registered[$student] = true;
return 'registered';
}
}
$event = new Event(1);
foreach ([7, 7, 8] as $student) {
echo $event->register($student), PHP_EOL;
}
echo (new Event(0))->register(7), PHP_EOL;
Checked output:
registered duplicate full full
10. Inheritance, interfaces, traits and exceptions
Interfaces define method contracts; inheritance specializes behavior; traits reuse method implementations. Exceptions are Throwable objects and propagate to a matching catch; finally supports cleanup.
Answer: No. Log useful details privately and return a safe error response without secrets.
11. Forms, superglobals and validation
GET, POST, COOKIE, SESSION and FILES expose different request data. An attacker can send arrays where a form expects strings. Validate presence, type, format, bounds and domain rules on the server.
Answer: No. Ownership or delivery needs a separate verification process.
Validate simulated form data and escape HTML
<?php
declare(strict_types=1);
function validate(array $input): array {
$id = $input['event_id'] ?? null;
$email = $input['email'] ?? null;
if (!is_string($id) || !preg_match('/\A[1-9][0-9]{0,5}\z/', $id)) {
throw new InvalidArgumentException('invalid event ID');
}
if (!is_string($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidArgumentException('invalid email');
}
return ['event_id' => (int) $id, 'email' => $email];
}
$valid = validate(['event_id' => '12', 'email' => 'learner@example.invalid']);
echo $valid['event_id'], PHP_EOL;
echo htmlspecialchars('<b>A & B</b>', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), PHP_EOL;
foreach ([[], ['event_id' => ['12'], 'email' => 'x'],
['event_id' => '12', 'email' => 'not-an-email']] as $input) {
try { validate($input); }
catch (InvalidArgumentException $e) { echo $e->getMessage(), PHP_EOL; }
}
Checked output:
12 <b>A & B</b> invalid event ID invalid event ID invalid email
12. Output escaping and XSS
Escape untrusted text for its output context. htmlspecialchars with ENT_QUOTES and ENT_SUBSTITUTE plus UTF-8 is appropriate for HTML text and quoted attributes, not automatically JavaScript, CSS or URL destinations.
Answer: Validation checks meaning and rules; escaping stops text being interpreted as syntax in a chosen output context.
13. GET, POST, status codes and redirects
GET should retrieve rather than change state. POST can request changes but still needs security checks. Send suitable status codes and content types; post-redirect-get reduces refresh resubmissions.
Answer: No. HTTPS protects transport; the method is not encryption.
14. Cookies and session lifecycle
Cookies are client-held data; a session commonly uses a cookie identifier to locate server-side state. Start sessions before output, configure cookies and expire idle/absolute lifetimes as appropriate.
Answer: No. Client values can be tampered with; use authenticated server-side identity and authorization.
15. Session fixation and authentication state
Use strict session handling and regenerate the identifier at appropriate authentication/privilege transitions. Session IDs are secrets and must not appear in URLs or logs. Logout must invalidate server-side authentication state.
Answer: No. It only starts or resumes session handling.
16. CSRF and authorization
Protect state-changing browser requests against cross-site request forgery with a suitable token/origin strategy and cookie policy. Validate permission on every sensitive action; CSRF protection and authorization are different controls.
Answer: No. Use defense matched to the application; cross-origin and same-site cases need careful handling.
17. Database connections and PDO
PDO provides a consistent data-access interface but requires a database-specific driver. Keep credentials out of public source and error output; set an explicit error/fetch policy and least-privilege database access.
Answer: No. Driver features and SQL dialect differences still matter.
18. Prepared statements and bound values
Prepared statements separate value parameters from SQL structure. Placeholders represent complete values, not table names, operators or keywords. Whitelist identifiers selected by the application.
Answer: No. They address SQL value injection; HTML still needs contextual output escaping.
19. Transactions, constraints and concurrency
A transaction groups related database changes. Database uniqueness and foreign-key constraints enforce integrity; capacity checks must use a concurrency strategy, not an unlocked count followed by insert.
Answer: No. Concurrent requests can both pass it; the database must enforce the rule.
Begin transaction -> lock / atomic capacity rule -> uniqueness-backed registration -> commit or rollback
20. Password storage and verification
Use password_hash and password_verify, never plaintext or reversible password storage. PASSWORD_DEFAULT can change algorithm/cost over time; allow sufficient hash-column space and use password_needs_rehash when policy changes.
Answer: No. Let the supported password-hashing API generate salts; choose resource costs for the deployment.
Password verification without printing the hash
<?php
declare(strict_types=1);
// Public teaching text, never use this as a real password.
$hash = password_hash('classroom-demo-only', PASSWORD_DEFAULT);
var_dump(password_verify('classroom-demo-only', $hash));
var_dump(password_verify('different-demo', $hash));
Checked output:
bool(true) bool(false)
21. Files, paths and cleanup
Check file-operation failures and close resources. Treat requested paths as untrusted; use application-owned paths and permissions. Do not serialize secrets into publicly reachable files.
Answer: A readable/writable path can expose private data or allow unwanted replacement, even when PHP syntax is correct.
22. Uploads and content checks
Treat uploaded filenames and MIME headers as untrusted. Validate upload errors, size and allowed content, use server-chosen names, store outside executable web paths where possible, and authorize downloads.
Answer: No. Extension, content and processing risks must be checked, and executable upload locations avoided.
23. Dates, timezones and server configuration
Use explicit timezones and immutable date objects where useful. A stored timestamp and a displayed local time are different representations. Deployment needs supported PHP versions, TLS and controlled error reporting.
Answer: No. Use server-side logging with public display disabled and without secrets in logs.
24. Regular expressions and parsing limits
Regex can validate simple text formats but is not a replacement for structured parsers. Bound input length and avoid patterns with excessive backtracking. preg_match returns 1,0 or false, which are distinct outcomes.
Answer: No. Use an appropriate HTML sanitizer and output context rules.
25. JSON and APIs
Encode/decode structured data with explicit failure handling, UTF-8 text and appropriate HTTP content type. JSON_THROW_ON_ERROR makes malformed input raise JsonException; validate the decoded schema separately.
Answer: No. A JSON response and JSON embedded in HTML have different output-context risks.
JSON round-trip and malformed input
<?php
declare(strict_types=1);
$data = ['event' => 12, 'seats' => 3];
$json = json_encode($data, JSON_THROW_ON_ERROR);
echo $json, PHP_EOL;
$decoded = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
echo $decoded['seats'], PHP_EOL;
try { json_decode('{broken}', true, 512, JSON_THROW_ON_ERROR); }
catch (JsonException $e) { echo 'invalid JSON', PHP_EOL; }
Checked output:
{"event":12,"seats":3}
3
invalid JSON
26. MVC, templates and routing
Separate request handling, domain rules, persistence and rendering. A router maps an allowed path/method to a handler; views render already-chosen data safely. Frameworks help structure work but do not remove security responsibilities.
Answer: It mixes responsibilities, exposes accidental outputs and makes testing/failure handling harder.
Route -> Controller -> Service -> Repository
|
View / JSON response27. Testing, logging and dependency care
Lint source, run unit tests for pure rules and integration tests for HTTP/database behavior. Test invalid, duplicate, unauthorized and concurrent paths. Log actionable failures without credentials, session IDs or unnecessary personal data.
Answer: No. Lint detects syntax errors, not logic, security, runtime configuration or concurrency faults.
28. Worked RSVP architecture
A complete RSVP flow authenticates, validates input and CSRF, authorizes the identity, checks event policy inside a transaction, enforces uniqueness/capacity, then responds with escaped output or a redirect..
Answer: Persistent transactional storage, authentication, authorization, CSRF, deployment configuration, rate controls, monitoring and full tests.
29. Revision and exam answer structure
Describe request inputs, validation, domain rules, data access, output context and failure behavior. Distinguish a runnable teaching demo from a production endpoint and identify required extensions/version.
Answer: SQL parameters, HTML escaping, authentication, authorization and CSRF each address a different failure class.
Security control reference
| Risk | Control | Does not replace |
|---|---|---|
| SQL value injection | Prepared statement parameters | Authorization / HTML escaping |
| XSS | Contextual output escaping | Input/domain validation |
| CSRF | Matched token/origin strategy | Authorization / XSS defense |
| Session theft/fixation | TLS,cookie policy,session lifecycle | Per-action access checks |
| Duplicate RSVP | Database uniqueness | Capacity transaction |
| Oversold seats | Locking or atomic database rule | Authentication |
| Unsafe upload | Content checks,limits,safe storage | Download authorization |
| Password exposure | Supported password hash/verify API | Rate controls and account security |
Demo boundary reference
| Example | Expected result | Scope |
|---|---|---|
| Marks39/40/100/101 | FAIL/PASS/PASS/invalid | Integer marks0..100 |
| Strict comparison | true then false | 0 vs text0 |
| Form input | ID12;escaped literal HTML | Syntax validation,not email ownership |
| Event capacity1 | registered/duplicate/full | No persistence or concurrent requests |
| Password verification | true/false | Public teaching text only |
| JSON | Round trip;malformed rejected | Decoded domain validation still needed |
Practical revision checklist
Trace request, identity, permission, validated values, database transaction and final output context. Test success plus malformed/array-shaped input, unauthorized access, duplicates, concurrency and error paths. The five CLI blocks are checked; a real deployment needs separate integration and security tests.
Resources and sources
Official language/API documentation and OWASP guidance support the rules. Explanations, diagrams and code on this page are original teaching material. Manual pages may include newer PHP features; these demos use PHP 8.1-compatible syntax.
Comments
Post a Comment