Overview
Handle failures with try, catch, finally, throw, and custom exception types.
PHP Exceptions 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 Exceptions 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
- Start PHP Exceptions with the incoming request data and the expected response.
- Validate and normalize input before calling helpers, models, or database code.
- Keep reusable logic in a function, class, model, or service instead of mixing everything into a view.
- Test both the success path and at least one validation or failure path.
Beginner Explanation
PHP Exceptions teaches defensive PHP habits for invalid input, runtime failures, and unsafe output.
Good PHP code expects wrong values, missing files, failed database calls, and unexpected user behavior.
Beginners should validate input, use exceptions or clear error handling, log developer details, and show users simple messages.
Before You Start
- Before practicing PHP Exceptions, 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
- filter_var can validate common values such as email, URL, integer, and IP address.
- try/catch handles expected failure paths without exposing internal details.
- htmlspecialchars protects HTML output from injected markup.
- Logs should capture developer details that users should not see.
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 Exceptions 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 Exceptions 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 Exceptions 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
try {
$email = trim($_POST['email'] ?? '');
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email address.');
}
echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8');
} catch (Throwable $error) {
error_log($error->getMessage());
echo 'Please check your input.';
}
Another Example
<?php
$email = trim($_POST['email'] ?? '');
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(422);
echo 'Enter a valid email address.';
exit;
}
echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8');
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 Exceptions 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 Exceptions 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
- Read the first lines to see whether the script returns HTML, JSON, text, or performs setup.
- Find every raw input source such as $_GET, $_POST, $_FILES, cookies, sessions, or database rows.
- Check the validation branch before the success branch.
- Check whether output is escaped or JSON encoded at the final boundary.
- For PHP Exceptions, 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 Exceptions 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 Exceptions 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 Exceptions, 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 Exceptions? 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 validation checklist for PHP Exceptions: list accepted input, rejected input, output escaping, exception handling, and what should be logged.
Mastery Check
- You can explain what request data PHP Exceptions 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.