exercises and solutions

Web PHP exercises

Web PHP exercises cross a request boundary. They should practise reading untrusted input, validating it, choosing a response, escaping HTML output, protecting state-changing actions, and preserving useful errors.

Example Exercise Shape

Build a profile-name form.

- Accept POST requests only.
- Trim the submitted name and reject an empty value.
- Redisplay validation errors.
- Escape the value when rendering it into HTML.
- Explain where CSRF protection belongs before production use.

Browser behaviour cannot be proved by assigning fake CLI variables. Use a local server, an HTTP client, or a framework test when the exercise needs the real request path.

Practice

Review A Profile Form

Describe the request flow for a profile-name form. Cover method checks, trimming, empty-value validation, escaped HTML redisplay, and where CSRF protection belongs.

Show solution

Accept the state change through POST, validate a CSRF token before processing, trim the submitted name, reject an empty value, and escape the value with htmlspecialchars() when rendering HTML.

Validation and output escaping solve different problems. Store the intended value; escape for the output context at render time.

Design A Safe Delete Request

Describe the request flow for deleting a saved address. Cover method choice, CSRF protection, authentication, ownership checks, missing records, redirect behaviour, and user-visible errors.

Show solution

Accept the state change through POST or DELETE, require an authenticated user, validate the CSRF token for a browser form, load the address, and authorise ownership before deleting it. Return a controlled not-found response when appropriate and redirect after success.

Authentication answers who the user is. Authorisation answers whether that user may delete this address.