Building an app
Requests and validation
This page covers reading request input with Taphra\Request, JSON bodies, uploaded files, the validator, and the two ways to validate in a controller: $this->validate() and form request classes. The full rule reference is in the validator package README.
Reading input
#Taphra\Request has static accessors over the current request. Nothing is sanitised on the way in: escape at the point of use (e() in HTML, bound values in SQL, json_encode() in JSON). The examples on this page use these routes:
# app/Config/routes.yml
GET:
/search: search/index
POST:
/api/posts: apiPost/store<?php
// app/Controllers/SearchController.php
namespace App\Controllers;
use Taphra\Request;
use Taphra\RestController;
class SearchController extends RestController
{
public function index(): string
{
return $this->json([
'q' => Request::str('q'), // trimmed string, '' when absent
'page' => Request::int('page', 1), // cast to int, 1 when absent
'exact' => Request::bool('exact'), // '1', 'true', 'on', 'yes' are true
'tags' => Request::array('tags'), // an array, a scalar wrapped in one
'filters' => Request::only(['lang', 'year']), // exactly these keys, null when absent
]);
}
}GET /search?q=+php+&page=2&tags[]=web&lang=en answers {"q":"php","page":2,"exact":false,"tags":["web"],"filters":{"lang":"en","year":null}}.
| Method | Returns |
|---|---|
Request::input($name, $default = null) |
the raw value from the form body or the query string (the body wins) |
Request::str(), int(), float(), bool(), array() |
the value cast to that type, or the default |
Request::only(array $keys), except(array $keys) |
a whitelisted or filtered array of input |
Request::fromGet($name), fromPost($name) |
a value from one source only |
Request::from('get'), from('post'), from('input') |
the same typed accessors bound to one source: Request::from('get')->int('page', 1) |
Request::GET(), Request::POST() |
the whole query string or form body as an array |
Request::requestMethod() |
GET, POST and so on, upper case |
Request::headers() |
request headers, keys like ACCEPT-LANGUAGE |
Request::server($key, $default = null) |
a $_SERVER value |
Request::uri(), referer(), userAgent(), isAjax() |
the path and query string, the Referer header, the User-Agent header, whether X-Requested-With: XMLHttpRequest was sent |
Request::clientIP() |
the client address (see below) |
Use only() (or a validator's validated fields) when you pass input to a DataStore, so a client cannot add columns you did not expect. DataStores also respect $fillable and $guarded (DataStores).
The client IP
#Request::clientIP() returns REMOTE_ADDR, the address the connection came from. Headers a client can set, such as X-Forwarded-For, count only when the connection comes from an address listed in app.trusted_proxies; the client is then the last address in X-Forwarded-For that is not itself a trusted proxy. Set trusted_proxies when the app runs behind a load balancer (Configuration), or every client gets the balancer's address.
JSON bodies
#PHP fills $_POST only for form submissions. With the skeleton's default index.php, a JSON request body is not in Request::input(); read it through a form request (which merges the JSON body into its input) or decode it yourself:
// in a controller action
$data = json_decode(\Taphra\Request::rawBody(), true) ?? [];With a PSR-15 pipeline in index.php (Routing), RequestBodyMiddleware parses JSON and form bodies and the dispatcher copies the result into $_POST, so Request::input() sees JSON fields too.
The raw body
#Request::rawBody() returns the body as the client sent it, byte for byte: what a webhook's signature is computed over, an XML document, a JSON text before decoding. On the PSR-15 entry it is the body of the PSR-7 request being dispatched, in route middleware (a signature check, say) as in the action, so an in-process test can send it (Testing); on the default entry it is php://input.
// in a RestController action receiving a signed webhook
$payload = \Taphra\Request::rawBody();
$expected = hash_hmac('sha256', $payload, (string) getenv('WEBHOOK_SECRET'));
if (!hash_equals($expected, (string) \Taphra\Request::server('HTTP_X_SIGNATURE', ''))) {
return $this->apiError(401, 'Bad signature');
}
$event = json_decode($payload, true);
if (!is_array($event)) {
return $this->apiError(400, 'The body is not JSON');
}
return $this->json(['received' => $event['event'] ?? null]);Uploaded files
#Uploads arrive in PHP's $_FILES. Taphra adds no upload wrapper, so check the error code, the size and the real content type before you keep a file, and store it under a name you generate, outside app/Static/:
// in a controller action handling <input type="file" name="avatar">
$file = $_FILES['avatar'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK || $file['size'] > 2_000_000) {
throw new \Taphra\Exceptions\HttpException(422, 'Send an image of at most 2 MB.');
}
$type = (new \finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
$ext = ['image/png' => 'png', 'image/jpeg' => 'jpg'][$type] ?? null;
if ($ext === null) {
throw new \Taphra\Exceptions\HttpException(422, 'Only PNG and JPEG images.');
}
move_uploaded_file($file['tmp_name'], APP_PATH . '/uploads/' . bin2hex(random_bytes(16)) . '.' . $ext);The form needs enctype="multipart/form-data"; $html->file('avatar') prints the input (Views and helpers).
The validator
#Taphra\Validator checks an array against rules written as pipe strings or arrays:
use Taphra\Validator;
$v = Validator::make(
['email' => 'alice@example', 'age' => '17', 'password' => 'hunter2', 'site' => 'javascript:alert(1)'],
[
'email' => 'required|email',
'age' => 'required|integer|min:18',
'password' => 'required|string|min:8',
'site' => 'nullable|url',
'role' => ['required', 'in:admin,editor'],
]
)->validate();
var_dump($v->fails()); // bool(true)
echo $v->firstError('age'), "\n"; // The age must be at least 18.
echo implode(', ', array_keys($v->errors())), "\n"; // email, age, password, site, roleThe built-in rules:
| Rule | Passes when the value |
|---|---|
required |
is present and not null, '' or [] |
nullable |
is anything; when it is null or '' the other rules are skipped |
sometimes |
is anything; when the field is absent the other rules are skipped |
email, url, domain, phone, json, date |
is an email address, a URL, a domain name, a phone number (7 to 15 digits, or phone:min,max), valid JSON, a date strtotime() reads |
string |
is text: a JSON number, boolean, list or object is not |
integer, numeric, boolean |
is an integer, a number, or one of true, false, 0, 1, "0", "1", "true", "false" |
alpha, alpha_num |
has ASCII letters only, or letters and digits only |
min:n, max:n |
has at least or at most n (see below) |
min_digits:n, max_digits:n |
has at least or at most n digit characters |
in:a,b,c, not_in:a,b,c |
is one of the listed values, or none of them |
confirmed, confirmed:other |
equals the field <name>_confirmation, or the named field |
regex:/pattern/ |
matches the pattern (use the array form when the pattern contains |) |
starts_with:x, ends_with:x |
starts or ends with the text |
unique:connection,table,column |
is not already in that column (add ,except_column,except_value to ignore the row being edited) |
Rules other than required, nullable and sometimes are skipped for an empty value. A few behaviours to know:
minandmaxmeasure strings by length. A number is compared by value; a numeric string is compared by value only when the field also hasintegerornumeric(integer|min:18rejects"17"); any other string is compared by its length in characters (min:8rejects"99"); an array by its number of elements. A JSON body can send a number or a list where you expect text, so addstringto text fields such as passwords:string|min:8rejects99and[1,2,3,4,5,6,7,8].urlacceptshttp,httpsandftponly.javascript:,data:andfile:URLs fail. List schemes to change that:url:httpsorurl:http,https,mailto.- An unknown rule throws. A rule name that is neither built in nor registered with
Validator::extend()throws anInvalidArgumentExceptionnaming the rule and the field, even when the field is empty, so a typo such asemialfails loudly instead of letting every value through. - An array value fails rules that expect a single value (
email,in,regexand the others).
Add your own rules with Validator::extend():
use Taphra\Validator;
Validator::extend(
'even',
fn (string $field, mixed $value, array $params, array $data): bool => is_numeric($value) && (int) $value % 2 === 0,
':field must be an even number'
);
$v = Validator::make(['seats' => '7'], ['seats' => 'required|even'])->validate();
echo $v->firstError('seats'), "\n"; // seats must be an even numberField names in messages
#Messages name a field by its input name. attributes() gives fields a readable name, used by every message, the built-in ones and the :field of your own rules alike. errors() stays keyed by the input name:
use Taphra\Validator;
$v = Validator::make(
['rate_limit_per_minute' => '0'],
['rate_limit_per_minute' => 'required|integer|min:1', 'webhook_url' => 'required|url']
)->attributes(['rate_limit_per_minute' => 'rate limit', 'webhook_url' => 'webhook address']);
echo $v->firstError('rate_limit_per_minute'), "\n"; // The rate limit must be at least 1.
echo $v->firstError('webhook_url'), "\n"; // The webhook address field is required.
echo implode(', ', array_keys($v->errors())), "\n"; // rate_limit_per_minute, webhook_urlA field without a name keeps its input name, so validators that do not call attributes() give the same messages as before. A form request names its fields in an attributes() method (below). $this->validate() in a controller uses the input names.
Validating in a controller
#$this->validate($data, $rules) validates and returns only the fields that have rules. When validation fails it ends the request itself:
- for a JSON request (
AcceptorContent-Typenamingapplication/json): status 422 with a problem-details body,{"type":"about:blank","title":"Unprocessable Entity","status":422,"detail":"The given data was invalid.","errors":{...}}; - otherwise: it stores the errors and the submitted input in the session (
_tphr_errorsand_tphr_old) and redirects back to theReferer(or/).
// app/Controllers/PostController.php (actions)
public function create(): void
{
$this->errors(); // read the errors flashed by a failed store()
$this->autoRender = true; // the form uses old() and error()
}
public function store(): void
{
$data = $this->validate(\Taphra\Request::POST(), [
'title' => 'required|max:200',
'body' => 'required',
]);
// $data has only title and body
$this->redirect('/posts');
}In the form view, old('title') refills the field and error('title', '<p class="error">%s</p>') shows the message (Forms and CSRF). To report an error the validator cannot see (a duplicate found by a query, say), call $this->withErrors(['title' => ['That title is taken.']], $data) and render the form again.
Form requests
#A form request is a class that holds the rules (and an authorisation check) for one action. Type-hint it on the action and the framework builds it from the query string, the form body and a JSON body, then calls authorize() before the action runs:
<?php
// app/Requests/StorePostRequest.php
namespace App\Requests;
use Taphra\FormRequest;
class StorePostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => 'required|max:200',
'status' => 'required|in:draft,published',
];
}
public function authorize(): bool
{
return true; // for example: \Taphra\Auth\Auth::check()
}
public function attributes(): array
{
return ['status' => 'publishing status']; // optional: names in the messages
}
}<?php
// app/Controllers/ApiPostController.php
namespace App\Controllers;
use App\Requests\StorePostRequest;
use Taphra\RestController;
class ApiPostController extends RestController
{
public function store(StorePostRequest $request): string
{
if ($request->fails()) {
return $this->apiError(422, 'Validation failed', ['errors' => $request->errors()]);
}
$data = $request->validated(); // only title and status
return $this->created($data);
}
}POST /api/posts with the JSON body {"title": "Hello", "status": "draft", "admin": true} answers 201 with {"title":"Hello","status":"draft"}; with {"status": "archived"} it answers 422 and lists the errors for title and status.
authorize()returning false stops the request with 403 before the action runs. Validation runs when the action first asks for it: checkfails()to answer with your own response, as above.validated()never returns input that failed the rules: it throwsTaphra\Exceptions\ValidationException, an HTTP 422 whoseerrors()holds the messages. Savingvalidated()data is therefore safe even in an action that forgetsfails().validated()returns only the fields named inrules();all(),get($key, $default)andhas($key)read the whole input;errors()returns the messages per field.attributes()is optional: it returns readable names for the fields, which the messages use (The selected publishing status is invalid.), asValidator::attributes()does.