-
-
Notifications
You must be signed in to change notification settings - Fork 2
Reading request data and streams
Input can do more than read HTML form fields. It also gives us access to the raw request body, JSON payloads, and request sections individually.
Use get() when we want the raw submitted value without converting it:
$search = $input->get("q");By default this reads from the combined request input. If we want to be explicit, we can choose a section of the request:
$page = $input->get("page", Input::DATA_QUERYSTRING);
$token = $input->get("token", Input::DATA_BODY);Use contains() when the difference between "missing" and "present but empty" matters:
if($input->contains("draft")) {
// The key exists somewhere in the request.
}There are also section-specific checks:
containsQueryStringParameter()containsBodyParameter()containsFile()
getAll() returns an InputData object:
$all = $input->getAll();
$query = $input->getAll(Input::DATA_QUERYSTRING);
$body = $input->getAll(Input::DATA_BODY);
$files = $input->getAll(Input::DATA_FILES);InputData is useful when we want to pass a subset of user input to another class or callback without handing over the whole request object.
If the request body contains JSON, use getBodyJson():
$json = $input->getBodyJson();
if($json) {
$email = $json->getString("email");
}If the body is not valid JSON, getBodyJson() returns null.
That makes it a good fit when the request might be JSON but we still want to detect invalid payloads in our own application flow.
To work with the raw request body directly, use getStream():
$stream = $input->getStream();
while(!feof($stream)) {
$chunk = fread($stream, 1024);
processBodyChunk($chunk);
}This is useful for non-form requests, custom formats, large payloads, or situations where another component expects a PSR-7 stream.
For PUT requests carrying file data in the body rather than through multipart/form-data, use getPutFileStream():
$stream = $input->getPutFileStream();
$fh = fopen("data/upload.bin", "w");
// memory efficient copy from incoming stream to file, for example purposes only (not really that useful in real world situations)
stream_copy_to_stream($stream, $fh);This method is only available when the request method is PUT. Calling it for another HTTP method throws StreamNotAvailableException.
Next: triggers and callbacks
PHP.GT/Input is a separately maintained component of PHP.GT/WebEngine.