⚡ TechVani: AI, Technology, Apps, Coding & Digital World
TechVaniAI • Technology • Apps • Coding • Digital World
HomeAI & TechAppsCodingFree AI ToolsStudent TechSecurityAboutContactPrivacy
TECHVANI // LEARN. BUILD. TEST.

Learn the tech. Build the idea.

Clear study notes, tested lab files and practical guides for coding, AI and digital safety.

Explore Latest →
šŸ¤– AI & TechAI news, tools & guides šŸ“± Apps & ToolsUseful apps & websites šŸ’» CodingProgramming & web development šŸŽ“ Student TechStudy & career technology šŸ” Cyber SecuritySafety & awareness

Latest Posts

Circuit Notebook theme

Exam Notes

šŸ“š BTech CSE Exam Notes

Find Semester 1-8 subjects in one place. Choose a semester and open the notes you need. This is a general study guide, not an official syllabus.

Open Exam Notes →🧪 Open Lab Files →

Exam Numericals & Study Series

Practice CPU scheduling and explore OS and DBMS topics in separate, easy-to-follow parts. New topics will appear in the hub as they are published.

Open Numericals Hub →

Start here and stay in touch

New to TechVani? Start with our free AI tools guide for students. It covers which tools to try and what to check before relying on an answer.

For step-by-step videos, visit SiteSudhar on YouTube.

Join TechVani on WhatsApp

Get new AI tools and coding guides in your WhatsApp Updates tab.

Browse Topics

Popular Posts

TechVani

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.

Run each block separately: save as 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

  1. Server-side request-response flow
  2. Syntax, variables and constants
  3. Types and deliberate conversion
  4. Operators, equality and control flow
  5. Functions, arguments and return types
  6. Strings, interpolation and encoding
  7. Arrays, keys and foreach
  8. Includes, namespaces and dependencies
  9. Classes, encapsulation and invariants
  10. Inheritance, interfaces, traits and exceptions
  11. Forms, superglobals and validation
  12. Output escaping and XSS
  13. GET, POST, status codes and redirects
  14. Cookies and session lifecycle
  15. Session fixation and authentication state
  16. CSRF and authorization
  17. Database connections and PDO
  18. Prepared statements and bound values
  19. Transactions, constraints and concurrency
  20. Password storage and verification
  21. Files, paths and cleanup
  22. Uploads and content checks
  23. Dates, timezones and server configuration
  24. Regular expressions and parsing limits
  25. JSON and APIs
  26. MVC, templates and routing
  27. Testing, logging and dependency care
  28. Worked RSVP architecture
  29. 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.

Worked example: GET /events reads a list; POST /rsvp requests a registration. The method alone does not authenticate, validate or authorize.
Exam question: Can a browser run PHP source directly as JavaScript?
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 browser
PHP source stays on the server when deployed correctly. HTTP output still needs its own security and encoding.

2. 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.

Worked example: $seats=10 and $Seats=10 name different variables. A pure PHP file usually omits its closing tag to avoid accidental trailing output.
Exam question: Why can stray output cause a headers-already-sent error?
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.

Worked example: A form value '12' arrives as text. Validate its format/range before converting it to an event identifier.
Exam question: Does declare(strict_types=1) validate a submitted form?
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.

Worked example: 0=='0' is true but 0==='0' is false. match uses strict comparison; switch uses loose comparison.
Exam question: Are loose comparison rules identical in PHP 7 and PHP 8?
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.

Worked example: grade(39)=FAIL,grade(40)=PASS,grade(100)=PASS; 101 throws an invalid-argument exception.
Exam question: Why test 39 and 40 together?
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.

Worked example: Concatenation uses a dot. strlen reports bytes, not a general Unicode character count; multibyte operations need the relevant extension.
Exam question: Does specifying UTF-8 make every incoming string valid?
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.

Worked example: An event array can contain id=>12,title=>'Seminar'. Missing keys need explicit handling rather than assumptions.
Exam question: Why unset the loop variable after foreach by reference?
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.

Worked example: Require a known configuration module outside public web access; do not turn a query parameter into an include path.
Exam question: Why not include a filename supplied by the visitor?
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.

Worked example: The Event demo accepts one unique student, labels a repeat duplicate, then labels another student full; capacity zero immediately gives full.
Exam question: Is this in-memory object a concurrent database booking system?
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.

Worked example: A repository interface can separate registration rules from persistence. Catch expected validation failures, not every failure as a successful response.
Exam question: Should internal exceptions be printed to public visitors?
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.

Worked example: The demo accepts a positive event-ID text of at most six digits and a syntactically valid email; [],array-valued ID and malformed email are rejected.
Exam question: Does valid email syntax prove ownership of that address?
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
&lt;b&gt;A &amp; B&lt;/b&gt;
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.

Worked example: <b>A & B</b> becomes literal HTML text when escaped. A safe-looking URL still needs an allowed scheme before insertion into href.
Exam question: Why separate validation from escaping?
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.

Worked example: After an accepted POST, send a 303 redirect to a confirmation GET and stop script execution. A redirect is not duplicate protection by itself.
Exam question: Does POST hide sensitive data from the network?
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.

Worked example: Secure cookies require HTTPS, HttpOnly limits script access, and SameSite controls cross-site sending behavior. None alone supplies authorization.
Exam question: Can you trust a role cookie saying admin?
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.

Worked example: After login, rotate the session identifier using a deliberate lifecycle strategy and set authenticated user state; handle concurrent requests according to the application design.
Exam question: Does session_start prove the visitor logged in?
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.

Worked example: A registration POST must belong to the logged-in student and carry the expected token. Compare secret tokens safely, after verifying both are strings.
Exam question: Does SameSite remove every CSRF risk?
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.

Worked example: A MySQL deployment needs the PDO MySQL driver and a suitable DSN. SQLite needs its own driver, not merely the base PDO extension.
Exam question: Does PDO make SQL portable automatically?
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.

Worked example: SELECT id FROM events WHERE id=:id binds an event value; ORDER BY :column does not safely choose a column name.
Exam question: Do prepared statements prevent XSS?
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.

Worked example: UNIQUE(event_id,student_id) prevents duplicate registration. A locked event row or atomic inventory update can guard capacity inside a transaction.
Exam question: Is a PHP-level duplicate check enough?
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
Database-specific concurrency control is required; a PHP count followed by an unlocked insert is not safe.

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.

Worked example: The public demo verifies one correct teaching string and rejects another, printing booleans rather than the salted hash. Its password is not for real use.
Exam question: Should salts be manually reused for every password?
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.

Worked example: A CSV export should use safe field formatting and a controlled download path. Never concatenate '../' input into a filesystem path.
Exam question: Why are permissions part of application correctness?
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.

Worked example: A claimed image can contain arbitrary content; inspect it with an appropriate parser and restrict accepted formats. move_uploaded_file checks upload provenance, not content safety.
Exam question: Is checking .jpg sufficient?
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.

Worked example: Store an event instant unambiguously, then display it in the chosen timezone. Do not assume a default server timezone matches students.
Exam question: Should production display all errors?
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.

Worked example: The event-ID demo anchors a small ASCII digit pattern with a positive first digit; arrays never reach regex evaluation.
Exam question: Does sanitizing arbitrary HTML with one regex make it safe?
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.

Worked example: The demo round-trips {event:12,seats:3}, then catches malformed JSON. A valid JSON object can still contain invalid domain fields.
Exam question: Is JSON encoding HTML output escaping?
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.

Worked example: Controller validates and authorizes RSVP; service enforces registration policy; repository performs transaction; template escapes the result.
Exam question: Why not put credentials and SQL inside every template?
Answer: It mixes responsibilities, exposes accidental outputs and makes testing/failure handling harder.
Route -> Controller -> Service -> Repository
                        |
                  View / JSON response
Separate policy and persistence from request parsing and output rendering. Every boundary has a contract.

27. 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.

Worked example: The five CLI demos here are executed on PHP 8.1; they do not test a live server, database, cookies, upload handling or production security.
Exam question: Does passing syntax check prove the program correct?
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..

Worked example: Two simultaneous students competing for one seat must not both be admitted. Database state is the authority, not a browser-provided seats count.
Exam question: What must a production version add beyond the demo?
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.

Worked example: For a form question, include array-shaped malicious input, invalid ID/email, duplicate registration, HTML-like names and a database failure.
Exam question: Which defenses are not interchangeable?
Answer: SQL parameters, HTML escaping, authentication, authorization and CSRF each address a different failure class.

Security control reference

RiskControlDoes not replace
SQL value injectionPrepared statement parametersAuthorization / HTML escaping
XSSContextual output escapingInput/domain validation
CSRFMatched token/origin strategyAuthorization / XSS defense
Session theft/fixationTLS,cookie policy,session lifecyclePer-action access checks
Duplicate RSVPDatabase uniquenessCapacity transaction
Oversold seatsLocking or atomic database ruleAuthentication
Unsafe uploadContent checks,limits,safe storageDownload authorization
Password exposureSupported password hash/verify APIRate controls and account security

Demo boundary reference

ExampleExpected resultScope
Marks39/40/100/101FAIL/PASS/PASS/invalidInteger marks0..100
Strict comparisontrue then false0 vs text0
Form inputID12;escaped literal HTMLSyntax validation,not email ownership
Event capacity1registered/duplicate/fullNo persistence or concurrent requests
Password verificationtrue/falsePublic teaching text only
JSONRound trip;malformed rejectedDecoded 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