PHP PHP Backend Development

Build server-side PHP skills for forms, sessions, files, databases, OOP, security, Laravel, and CodeIgniter-style MVC.

Lessons

Sign in to save progress
1 PHP Tutorial 2 PHP HOME 3 PHP Intro 4 PHP Install 5 PHP Syntax 6 PHP Comments 7 PHP Variables 8 PHP Echo / Print 9 PHP Data Types 10 PHP Strings 11 PHP Numbers 12 PHP Casting 13 PHP Math 14 PHP Constants 15 PHP Magic Constants 16 PHP Operators 17 PHP If...Else...Elseif 18 PHP Switch 19 PHP Match 20 PHP Loops 21 PHP Functions 22 PHP Arrays 23 PHP Superglobals 24 PHP RegEx 25 PHP RegEx Functions 26 PHP Forms 27 PHP Form Handling 28 PHP Form Validation 29 PHP Form Required 30 PHP Form URL/E-mail 31 PHP Form Complete 32 PHP Date and Time 33 PHP Include 34 PHP File Handling 35 PHP File Open/Read 36 PHP File Create/Write 37 PHP File Upload 38 PHP Cookies 39 PHP Sessions 40 PHP Filters 41 PHP Filters Advanced 42 PHP Callback Functions 43 PHP JSON 44 PHP Exceptions 45 PHP OOP 46 PHP What is OOP 47 PHP Classes/Objects 48 PHP Constructor 49 PHP Destructor 50 PHP Access Modifiers 51 PHP Inheritance 52 PHP Constants 53 PHP Abstract Classes 54 PHP Interfaces 55 PHP Traits 56 PHP Static Methods 57 PHP Static Properties 58 PHP Namespaces 59 PHP Iterables 60 MySQL Database 61 MySQL Connect 62 MySQL Create DB 63 MySQL Create Table 64 MySQL Insert Data 65 MySQL Get Last ID 66 MySQL Insert Multiple 67 MySQL Prepared 68 MySQL Select Data 69 MySQL Where 70 MySQL Order By 71 MySQL Delete Data 72 MySQL Update Data 73 MySQL Limit Data 74 PHP XML 75 PHP XML Parsers 76 PHP SimpleXML Parser 77 PHP SimpleXML - Get 78 PHP XML Expat Parser 79 PHP DOM Parser 80 PHP - AJAX 81 AJAX Intro 82 AJAX PHP 83 AJAX Database 84 AJAX XML 85 AJAX Live Search 86 AJAX Poll 87 PHP Cert 88 PHP Certificate 89 PHP Examples 90 PHP Compiler 91 PHP Quiz 92 PHP Exercises 93 PHP Practice Problems 94 PHP Server 95 PHP Syllabus 96 PHP Study Plan 97 PHP Overview 98 PHP Array 99 PHP Calendar 100 PHP Date 101 PHP Directory 102 PHP Error 103 PHP Exception 104 PHP Filesystem 105 PHP Filter 106 PHP FTP 107 PHP JSON 108 PHP Keywords 109 PHP Libxml 110 PHP Mail 111 PHP Math 112 PHP Misc 113 PHP MySQLi 114 PHP Network 115 PHP Output Control 116 PHP RegEx 117 PHP SimpleXML 118 PHP Stream 119 PHP String 120 PHP Variable Handling 121 PHP XML Parser 122 PHP Zip 123 PHP Timezones

PHP Match

PHP Backend Development Lesson 19 of 123 ~11 min read

Overview

Return values from strict branch expressions using match.

PHP Match is server-side code that receives a request, runs application logic, talks to storage, and returns a response. Strong PHP code validates input, escapes output, and keeps business logic organized.

Core Ideas

  • Use PHP Match to handle one request or one reusable piece of server logic.
  • Validate input before using it and escape output before sending it to HTML.
  • Keep database work parameterized and separated from presentation code.
  • Return clear responses for success, validation errors, and unexpected failures.

Step by Step

  1. Start PHP Match with the incoming request data and the expected response.
  2. Validate and normalize input before calling helpers, models, or database code.
  3. Keep reusable logic in a function, class, model, or service instead of mixing everything into a view.
  4. Test both the success path and at least one validation or failure path.

Beginner Explanation

PHP Match controls when PHP code runs, repeats, returns, or delegates work.

Conditionals, loops, functions, callbacks, and match expressions make code easier to read when each block has one job.

Beginners should name functions clearly and return values instead of echoing from every helper.

Before You Start

  • Before practicing PHP Match, know whether your code is running from the command line or through a web server.
  • Turn on error reporting in development so mistakes are visible while you learn.
  • Use a small sample file, form, or database table before touching real project data.
  • Decide what input your script accepts and what output it should return.
  • Keep secrets such as database passwords in configuration, not inside lesson examples or public files.

Key PHP Concepts

  • if, switch, and match choose between branches.
  • for, while, and foreach repeat work.
  • Functions should have clear inputs and return values.
  • Callbacks and closures let you pass behavior into other functions.

Plain-English Glossary

  • Request: the browser or client asking the server for something.
  • Response: what PHP sends back after running code.
  • Superglobal: a built-in array such as $_GET, $_POST, $_SERVER, $_SESSION, or $_FILES.
  • Validation: checking whether input is acceptable for the action.
  • Escaping: converting output so it is safe in HTML, SQL, JSON, or another context.
  • Prepared statement: a database statement that binds values separately from SQL text.
  • Class: a reusable blueprint for objects.
  • Exception: a structured way to signal and handle a failure.

What You Will Learn

  • Explain what PHP Match does in the PHP request-response flow.
  • Identify the input values, output values, and possible failure cases.
  • Write a small safe example that validates input and escapes output where needed.
  • Describe one real project feature where this PHP topic would appear.

Where You Use This in Real Projects

You use PHP Match in contact forms, login systems, dashboards, admin panels, APIs, uploads, reports, CMS pages, payment callbacks, imports, exports, and background scripts.

PHP is valuable because it can combine request data, database records, templates, files, and external services into one server response.

A careful PHP workflow is: read input, validate it, call focused logic, persist data safely, escape output, and handle errors predictably.

PHP Safety Notes

  • Validate every value from forms, query strings, cookies, sessions, uploads, APIs, and databases before trusting it for a specific purpose.
  • Escape output with the correct escaping function for the context, especially HTML output.
  • Use prepared statements for database input and avoid building SQL with raw strings.
  • Do not reveal stack traces, file paths, database errors, or secrets to public users.
  • Keep writable folders outside public assets when possible, and never execute uploaded files.

Beginner Mental Model

Think of PHP Match as one step in a server conversation.

The browser asks for something, PHP gathers data and makes decisions, then the server sends back a response.

Good PHP code separates raw input, trusted data, business rules, storage, and presentation so mistakes are easier to find.

Code Example

<?php

function progressLabel(int $percent): string
{
    return match (true) {
        $percent >= 100 => 'complete',
        $percent >= 50 => 'in progress',
        default => 'started',
    };
}

foreach ([15, 60, 100] as $percent) {
    echo progressLabel($percent) . PHP_EOL;
}

Another Example

<?php

function statusLabel(int $score): string
{
    return match (true) {
        $score >= 90 => 'excellent',
        $score >= 70 => 'good',
        default => 'keep practicing',
    };
}

foreach ([95, 74, 48] as $score) {
    echo statusLabel($score) . PHP_EOL;
}

More Practice Examples

Example 1: Validate and escape input

<?php

$username = trim($_POST['username'] ?? '');

if ($username === '') {
    echo 'Username is required.';
    exit;
}

echo 'Welcome ' . htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
  • trim removes accidental spaces before validation.
  • The empty check catches missing input early.
  • htmlspecialchars makes the output safe for an HTML page.

Example 2: Reusable function

<?php

function lessonSlug(string $title): string
{
    $slug = strtolower(trim($title));
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);

    return trim($slug, '-');
}

echo lessonSlug('PHP Beginner Tutorial');
  • The function accepts one input and returns one output.
  • preg_replace changes groups of non-alphanumeric characters into dashes.
  • Returning the value makes the function reusable in tests and other scripts.

Example 3: Prepared database lookup

<?php

$stmt = $pdo->prepare('SELECT id, title FROM lessons WHERE slug = :slug');
$stmt->execute(['slug' => $_GET['slug'] ?? 'php-tutorial']);

$lesson = $stmt->fetch(PDO::FETCH_ASSOC);

if ($lesson) {
    echo htmlspecialchars($lesson['title'], ENT_QUOTES, 'UTF-8');
}
  • The placeholder keeps the SQL shape separate from the user value.
  • fetch returns one row or false when nothing matched.
  • Database values are still escaped before being printed into HTML.

Real-World Request Pattern

<?php

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

try {
    $email = trim($_POST['email'] ?? '');

    if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(422);
        echo json_encode(['ok' => false, 'message' => 'Enter a valid email.'], JSON_THROW_ON_ERROR);
        exit;
    }

    $stmt = $pdo->prepare('INSERT INTO subscribers (email) VALUES (:email)');
    $stmt->execute(['email' => $email]);

    echo json_encode(['ok' => true, 'message' => 'Subscribed.'], JSON_THROW_ON_ERROR);
} catch (Throwable $error) {
    error_log($error->getMessage());
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => 'Please try again later.'], JSON_THROW_ON_ERROR);
}
  • This PHP Match pattern shows a complete PHP request: headers, input, validation, database work, success response, and failure response.
  • The user sees a simple message, while developer details go to the log.
  • Prepared statements, validation, and JSON encoding make the endpoint safer and easier to debug.

Example Explained

  • The PHP Match example starts by reading the value or resource the script needs.
  • Validation happens before the value is used for storage, output, file access, or branching.
  • Reusable code is placed in functions or classes when the logic has a clear name.
  • Output is escaped for HTML or encoded as JSON depending on the response type.
  • Errors are handled deliberately instead of letting raw internal details leak to users.

How to Read This Example

  1. Read the first lines to see whether the script returns HTML, JSON, text, or performs setup.
  2. Find every raw input source such as $_GET, $_POST, $_FILES, cookies, sessions, or database rows.
  3. Check the validation branch before the success branch.
  4. Check whether output is escaped or JSON encoded at the final boundary.
  5. For PHP Match, change one input value and predict the response before running the script.

Checklist

  • Turn on strict types for new PHP files when possible.
  • Validate input, escape output, and use prepared statements for database work.
  • Keep controllers thin and move reusable logic into models, services, or classes.

Common Mistakes

  • Trusting $_GET, $_POST, cookies, uploaded files, or session data without validation.
  • Echoing user content into HTML without escaping it.
  • Putting database queries, validation, and HTML templates into one tangled script.

Do and Don't

  • Do: practice PHP Match with small scripts before mixing it into a full project.
  • Do: validate input, escape output, and use prepared statements for database values.
  • Do: name variables, functions, classes, and files after what they actually do.
  • Don't: trust browser input, uploaded filenames, cookies, sessions, or database text automatically.
  • Don't: show raw errors, stack traces, SQL errors, or secret paths to public users.

Practice Challenge

Open the PHP Match starter in the code editor, change one input or validation rule, then explain what the server would return for valid and invalid requests.

Try These Changes

  • Add one required field and write the validation message.
  • Change the output from HTML text to a JSON response.
  • Move repeated logic into a small function with a return type.
  • Add one try/catch block around a file or database operation.
  • For PHP Match, write down which values are raw input and which values are safe to output.

Quick Check

  • Question: Where does PHP run? Answer: On the server before the response reaches the browser.
  • Question: Why validate input? Answer: To confirm the value is acceptable for the action.
  • Question: Why escape output? Answer: To prevent user-controlled text from becoming HTML or script.
  • Question: Why use prepared statements? Answer: To bind values separately from SQL command text.
  • Question: What should you identify first in PHP Match? Answer: The input, expected output, and failure cases.

Debugging Checks

  • Check the PHP error log and enable useful development error reporting.
  • Confirm the request method, field names, and content type match what the script expects.
  • Dump small values during learning, but remove debug output before returning public responses.
  • Check file paths with __DIR__ and confirm permissions for writable folders.
  • For database code, check DSN, credentials, prepared parameters, and the exact exception message in logs.

Mini Project

Build a small grading script for PHP Match: use a function, match or if branches, foreach loops, and return labels for several scores.

Mastery Check

  • You can explain what request data PHP Match accepts and what response it returns.
  • You can point to where validation, escaping, persistence, and errors are handled.
  • You can refactor the example into a reusable function, class, controller, or model.
Create a free account to save which lessons you've finished. Save my progress