The request and response objects provide an abstraction around HTTP requests and
responses. The request object in CakePHP allows you to introspect an incoming
request, while the response object allows you to effortlessly create HTTP
responses from your controllers.
Request
-
class Cake\Http\ServerRequest
ServerRequest
is the default request object used in CakePHP. It centralizes a
number of features for interrogating and interacting with request data.
On each request one Request is created and then passed by reference to the
various layers of an application that use request data. By default the request
is assigned to $this->request
, and is available in Controllers, Cells, Views
and Helpers. You can also access it in Components using the controller
reference.
Changed in version 4.4.0: The ServerRequest
is available via DI.
So you can get it from container or use it as a dependency for your service.
Some of the duties ServerRequest
performs include:
Processing the GET, POST, and FILES arrays into the data structures you are
familiar with.
Providing environment introspection pertaining to the request. Information
like the headers sent, the client’s IP address, and the subdomain/domain
names the server your application is running on.
Providing access to request parameters both as array indexes and object
properties.
CakePHP’s request object implements the PSR-7
ServerRequestInterface making it easier to
use libraries from outside of CakePHP.
Request Parameters
The request exposes routing parameters through the getParam()
method:
$controllerName = $this->request->getParam('controller');
To get all routing parameters as an array use getAttribute()
:
$parameters = $this->request->getAttribute('params');
All Route Elements are accessed through this interface.
In addition to Route Elements, you also often need access to
Passed Arguments. These are both available on the request object as
well:
// Passed arguments
$passedArgs = $this->request->getParam('pass');
Will all provide you access to the passed arguments. There
are several important/useful parameters that CakePHP uses internally, these
are also all found in the routing parameters:
plugin
The plugin handling the request. Will be null when there is no
plugin.
controller
The controller handling the current request.
action
The action handling the current request.
prefix
The prefix for the current action. See Prefix Routing for
more information.
Query String Parameters
-
Cake\Http\ServerRequest::getQuery($name, $default = null)
Query string parameters can be read using the getQuery()
method:
// URL is /posts/index?page=1&sort=title
$page = $this->request->getQuery('page');
You can either directly access the query property, or you can use
getQuery()
method to read the URL query array in an error-free manner.
Any keys that do not exist will return null
:
$foo = $this->request->getQuery('value_that_does_not_exist');
// $foo === null
// You can also provide default values
$foo = $this->request->getQuery('does_not_exist', 'default val');
If you want to access all the query parameters you can use
getQueryParams()
:
$query = $this->request->getQueryParams();
You can use the casting utility functions to provide typesafe access to request
data and other input:
use function Cake\Core\toBool;
use function Cake\Core\toInt;
use function Cake\Core\toString;
use function Cake\I18n\toDate;
use function Cake\I18n\toDateTime;
// $active is bool|null.
$active = toBool($this->request->getQuery('active'));
// $page is int|null.
$page = toInt($this->request->getQuery('page'));
// $query is string|null.
$query = toString($this->request->getQuery('query'));
// Parse a date based on the format or null
$date = toDate($this->request->getQuery('date'), 'Y-m-d');
// Parse a datetime based on a format or null
$date = toDateTime($this->request->getQuery('datetime'), 'Y-m-d H:i:s');
Added in version 5.1.0: Casting functions were added.
Request Body Data
-
Cake\Http\ServerRequest::getData($name, $default = null)
All POST data normally available through PHP’s $_POST
global variable can be
accessed using Cake\Http\ServerRequest::getData()
. For example:
// An input with a name attribute equal to 'title' is accessible at
$title = $this->request->getData('title');
You can use a dot separated names to access nested data. For example:
$value = $this->request->getData('address.street_name');
For non-existent names the $default
value will be returned:
$foo = $this->request->getData('value.that.does.not.exist');
// $foo == null
You can also use Body Parser Middleware to parse request body of different
content types into an array, so that it’s accessible through ServerRequest::getData()
.
If you want to access all the data parameters you can use
getParsedBody()
:
$data = $this->request->getParsedBody();
File Uploads
Uploaded files can be accessed through the request body data, using the Cake\Http\ServerRequest::getData()
method described above. For example, a file from an input element with a name attribute of attachment
, can
be accessed like this:
$attachment = $this->request->getData('attachment');
By default file uploads are represented in the request data as objects that implement
\Psr\Http\Message\UploadedFileInterface. In the current
implementation, the $attachment
variable in the above example would by default hold an instance of
\Laminas\Diactoros\UploadedFile
.
Accessing the uploaded file details is fairly simple, here’s how you can obtain the same data as provided by the old
style file upload array:
$name = $attachment->getClientFilename();
$type = $attachment->getClientMediaType();
$size = $attachment->getSize();
$tmpName = $attachment->getStream()->getMetadata('uri');
$error = $attachment->getError();
Moving the uploaded file from its temporary location to the desired target
location, doesn’t require manually accessing the temporary file, instead it can
be easily done by using the objects moveTo()
method:
$attachment->moveTo($targetPath);
In an HTTP environment, the moveTo()
method will automatically validate
whether the file is an actual uploaded file, and throw an exception in case
necessary. In an CLI environment, where the concept of uploading files doesn’t
exist, it will allow to move the file that you’ve referenced irrespective of its
origins, which makes testing file uploads possible.
-
Cake\Http\ServerRequest::getUploadedFile($path)
Returns the uploaded file at a specific path. The path uses the same dot syntax as the
Cake\Http\ServerRequest::getData()
method:
$attachment = $this->request->getUploadedFile('attachment');
Unlike Cake\Http\ServerRequest::getData()
, Cake\Http\ServerRequest::getUploadedFile()
would
only return data when an actual file upload exists for the given path, if there is regular, non-file request body data
present at the given path, then this method will return null
, just like it would for any non-existent path.
-
Cake\Http\ServerRequest::getUploadedFiles()
Returns all uploaded files in a normalized array structure. For the above example with the file input name of
attachment
, the structure would look like:
[
'attachment' => object(Laminas\Diactoros\UploadedFile) {
// ...
}
]
-
Cake\Http\ServerRequest::withUploadedFiles(array $files)
This method sets the uploaded files of the request object, it accepts an array of objects that implement
\Psr\Http\Message\UploadedFileInterface. It will
replace all possibly existing uploaded files:
$files = [
'MyModel' => [
'attachment' => new \Laminas\Diactoros\UploadedFile(
$streamOrFile,
$size,
$errorStatus,
$clientFilename,
$clientMediaType
),
'anotherAttachment' => new \Laminas\Diactoros\UploadedFile(
'/tmp/hfz6dbn.tmp',
123,
\UPLOAD_ERR_OK,
'attachment.txt',
'text/plain'
),
],
];
$this->request = $this->request->withUploadedFiles($files);
Note
Uploaded files that have been added to the request via this method, will not be available in the request body
data, ie you cannot retrieve them via Cake\Http\ServerRequest::getData()
! If you need them in the
request data (too), then you have to set them via Cake\Http\ServerRequest::withData()
or
Cake\Http\ServerRequest::withParsedBody()
.
PUT, PATCH or DELETE Data
-
Cake\Http\ServerRequest::getBody()
When building REST services, you often accept request data on PUT
and
DELETE
requests. Any application/x-www-form-urlencoded
request body data
will automatically be parsed and available via $request->getData()
for PUT
and
DELETE
requests. If you are accepting JSON or XML data, you can
access the raw data with getBody()
:
// Get the stream wrapper on the request body
$body = $request->getBody();
// Get the request body as a string
$bodyString = (string)$request->getBody();
If your requests contain XML or JSON request content, you should consider using
Body Parser Middleware to have CakePHP automatically parse those content
types making the parsed data available in $request->getData()
and
$request->getParsedBody()
.
Environment Variables (from $_SERVER and $_ENV)
-
Cake\Http\ServerRequest::getEnv($key, $default = null)
ServerRequest::getEnv()
is a wrapper for getenv()
global function and acts as
a getter for environment variables without possible undefined keys:
$host = $this->request->getEnv('HTTP_HOST');
To access all the environment variables in a request use getServerParams()
:
$env = $this->request->getServerParams();
-
Cake\Http\ServerRequest::withEnv($key, $value)
ServerRequest::withEnv()
is a wrapper for putenv()
global function and acts as
a setter for environment variables without having to modify globals
$_SERVER
and $_ENV
:
// Set a value, generally helpful in testing.
$this->request->withEnv('REQUEST_METHOD', 'POST');
XML or JSON Data
Applications employing REST often exchange data in
non-URL-encoded post bodies. You can read input data in any format using
input()
. By providing a decoding function,
you can receive the content in a deserialized format:
// Get JSON encoded data submitted to a PUT/POST action
$jsonData = $this->request->input('json_decode');
Some deserializing methods require additional parameters when called, such as
the ‘as array’ parameter on json_decode
. If you want XML converted into a
DOMDocument object, input()
supports
passing in additional parameters as well:
// Get XML encoded data submitted to a PUT/POST action
$data = $this->request->input('Cake\Utility\Xml::build', ['return' => 'domdocument']);
Checking Request Conditions
-
Cake\Http\ServerRequest::is($type, $args...)
The request object provides a way to inspect certain conditions in a given
request. By using the is()
method you can check a number of common
conditions, as well as inspect other application specific request criteria:
$isPost = $this->request->is('post');
You can also extend the request detectors that are available, by using
Cake\Http\ServerRequest::addDetector()
to create new kinds of
detectors. There are different types of detectors that you can create:
Environment value comparison - Compares a value fetched from env()
for equality with the provided value.
Header value comparison - If the specified header exists with the specified
value, or if the callable returns true.
Pattern value comparison - Pattern value comparison allows you to compare a
value fetched from env()
to a regular expression.
Option based comparison - Option based comparisons use a list of options to
create a regular expression. Subsequent calls to add an already defined
options detector will merge the options.
Callback detectors - Callback detectors allow you to provide a ‘callback’ type
to handle the check. The callback will receive the request object as its only
parameter.
-
Cake\Http\ServerRequest::addDetector($name, $options)
Some examples would be:
// Add an environment detector.
$this->request->addDetector(
'post',
['env' => 'REQUEST_METHOD', 'value' => 'POST']
);
// Add a pattern value detector.
$this->request->addDetector(
'iphone',
['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']
);
// Add an option detector
$this->request->addDetector('internalIp', [
'env' => 'CLIENT_IP',
'options' => ['192.168.0.101', '192.168.0.100']
]);
// Add a header detector with value comparison
$this->request->addDetector('fancy', [
'env' => 'CLIENT_IP',
'header' => ['X-Fancy' => 1]
]);
// Add a header detector with callable comparison
$this->request->addDetector('fancy', [
'env' => 'CLIENT_IP',
'header' => ['X-Fancy' => function ($value, $header) {
return in_array($value, ['1', '0', 'yes', 'no'], true);
}]
]);
// Add a callback detector. Must be a valid callable.
$this->request->addDetector(
'awesome',
function ($request) {
return $request->getParam('awesome');
}
);
// Add a detector that uses additional arguments.
$this->request->addDetector(
'csv',
[
'accept' => ['text/csv'],
'param' => '_ext',
'value' => 'csv',
]
);
There are several built-in detectors that you can use:
is('get')
Check to see whether the current request is a GET.
is('put')
Check to see whether the current request is a PUT.
is('patch')
Check to see whether the current request is a PATCH.
is('post')
Check to see whether the current request is a POST.
is('delete')
Check to see whether the current request is a DELETE.
is('head')
Check to see whether the current request is HEAD.
is('options')
Check to see whether the current request is OPTIONS.
is('ajax')
Check to see whether the current request came with
X-Requested-With = XMLHttpRequest.
is('ssl')
Check to see whether the request is via SSL.
is('flash')
Check to see whether the request has a User-Agent of Flash.
is('json')
Check to see whether the request URL has ‘json’ extension or the
Accept header is set to ‘application/json’.
is('xml')
Check to see whether the request URL has ‘xml’ extension or the Accept header is set to
‘application/xml’ or ‘text/xml’.
ServerRequest
also includes methods like
Cake\Http\ServerRequest::domain()
,
Cake\Http\ServerRequest::subdomains()
and
Cake\Http\ServerRequest::host()
to make applications that use
subdomains simpler.
Session Data
To access the session for a given request use the getSession()
method or use the session
attribute:
$session = $this->request->getSession();
$session = $this->request->getAttribute('session');
$data = $session->read('sessionKey');
For more information, see the Sessions documentation for how
to use the session object.
Host and Domain Name
-
Cake\Http\ServerRequest::domain($tldLength = 1)
Returns the domain name your application is running on:
// Prints 'example.org'
echo $request->domain();
-
Cake\Http\ServerRequest::subdomains($tldLength = 1)
Returns the subdomains your application is running on as an array:
// Returns ['my', 'dev'] for 'my.dev.example.org'
$subdomains = $request->subdomains();
-
Cake\Http\ServerRequest::host()
Returns the host your application is on:
// Prints 'my.dev.example.org'
echo $request->host();
Reading the HTTP Method
-
Cake\Http\ServerRequest::getMethod()
Returns the HTTP method the request was made with:
// Output POST
echo $request->getMethod();
Restricting Which HTTP method an Action Accepts
-
Cake\Http\ServerRequest::allowMethod($methods)
Set allowed HTTP methods. If not matched, will throw
MethodNotAllowedException
. The 405 response will include the required
Allow
header with the passed methods:
public function delete()
{
// Only accept POST and DELETE requests
$this->request->allowMethod(['post', 'delete']);
...
}
Reading Cookies
Request cookies can be read through a number of methods:
// Get the cookie value, or null if the cookie is missing.
$rememberMe = $this->request->getCookie('remember_me');
// Read the value, or get the default of 0
$rememberMe = $this->request->getCookie('remember_me', 0);
// Get all cookies as an hash
$cookies = $this->request->getCookieParams();
// Get a CookieCollection instance
$cookies = $this->request->getCookieCollection()
See the Cake\Http\Cookie\CookieCollection
documentation for how
to work with cookie collection.
Uploaded Files
Requests expose the uploaded file data in getData()
or
getUploadedFiles()
as UploadedFileInterface
objects:
// Get a list of UploadedFile objects
$files = $request->getUploadedFiles();
// Read the file data.
$files[0]->getStream();
$files[0]->getSize();
$files[0]->getClientFileName();
// Move the file.
$files[0]->moveTo($targetPath);
Manipulating URIs
Requests contain a URI object, which contains methods for interacting with the
requested URI:
// Get the URI
$uri = $request->getUri();
// Read data out of the URI.
$path = $uri->getPath();
$query = $uri->getQuery();
$host = $uri->getHost();
Response
-
class Cake\Http\Response
Cake\Http\Response
is the default response class in CakePHP.
It encapsulates a number of features and functionality for generating HTTP
responses in your application. It also assists in testing, as it can be
mocked/stubbed allowing you to inspect headers that will be sent.
Response
provides an interface to wrap the common response-related
tasks such as:
Sending headers for redirects.
Sending content type headers.
Sending any header.
Sending the response body.
Dealing with Content Types
-
Cake\Http\Response::withType($contentType = null)
You can control the Content-Type of your application’s responses with
Cake\Http\Response::withType()
. If your application needs to deal
with content types that are not built into Response, you can map them with
setTypeMap()
as well:
// Add a vCard type
$this->response->setTypeMap('vcf', ['text/v-card']);
// Set the response Content-Type to vcard.
$this->response = $this->response->withType('vcf');
Usually, you’ll want to map additional content types in your controller’s
beforeFilter()
callback, so you can benefit from
automatic view switching provided by Content Type Negotiation.
Sending Files
-
Cake\Http\Response::withFile(string $path, array $options = [])
There are times when you want to send files as responses for your requests.
You can accomplish that by using Cake\Http\Response::withFile()
:
public function sendFile($id)
{
$file = $this->Attachments->getFile($id);
$response = $this->response->withFile($file['path']);
// Return the response to prevent controller from trying to render
// a view.
return $response;
}
As shown in the above example, you must pass the file path to the method.
CakePHP will send a proper content type header if it’s a known file type listed
in Cake\Http\Response::$_mimeTypes. You can add new types prior to calling
Cake\Http\Response::withFile()
by using the
Cake\Http\Response::withType()
method.
If you want, you can also force a file to be downloaded instead of displayed in
the browser by specifying the options:
$response = $this->response->withFile(
$file['path'],
['download' => true, 'name' => 'foo']
);
The supported options are:
- name
The name allows you to specify an alternate file name to be sent to
the user.
- download
A boolean value indicating whether headers should be set to force
download.
Sending a String as File
You can respond with a file that does not exist on the disk, such as a pdf or an
ics generated on the fly from a string:
public function sendIcs()
{
$icsString = $this->Calendars->generateIcs();
$response = $this->response;
// Inject string content into response body
$response = $response->withStringBody($icsString);
$response = $response->withType('ics');
// Optionally force file download
$response = $response->withDownload('filename_for_download.ics');
// Return response object to prevent controller from trying to render
// a view.
return $response;
}
Setting the Body
-
Cake\Http\Response::withStringBody($string)
To set a string as the response body, do the following:
// Set a string into the body
$response = $response->withStringBody('My Body');
// If you want a json response
$response = $response->withType('application/json')
->withStringBody(json_encode(['Foo' => 'bar']));
-
Cake\Http\Response::withBody($body)
To set the response body, use the withBody()
method, which is provided by the
Laminas\Diactoros\MessageTrait
:
$response = $response->withBody($stream);
Be sure that $stream
is a Psr\Http\Message\StreamInterface
object.
See below on how to create a new stream.
You can also stream responses from files using Laminas\Diactoros\Stream
streams:
// To stream from a file
use Laminas\Diactoros\Stream;
$stream = new Stream('/path/to/file', 'rb');
$response = $response->withBody($stream);
You can also stream responses from a callback using the CallbackStream
. This
is useful when you have resources like images, CSV files or PDFs you need to
stream to the client:
// Streaming from a callback
use Cake\Http\CallbackStream;
// Create an image.
$img = imagecreate(100, 100);
// ...
$stream = new CallbackStream(function () use ($img) {
imagepng($img);
});
$response = $response->withBody($stream);
Setting the Character Set
-
Cake\Http\Response::withCharset($charset)
Sets the charset that will be used in the response:
$this->response = $this->response->withCharset('UTF-8');
Interacting with Browser Caching
-
Cake\Http\Response::withDisabledCache()
You sometimes need to force browsers not to cache the results of a controller
action. Cake\Http\Response::withDisabledCache()
is intended for just
that:
public function index()
{
// Disable caching
$this->response = $this->response->withDisabledCache();
}
Warning
Disabling caching from SSL domains while trying to send
files to Internet Explorer can result in errors.
-
Cake\Http\Response::withCache($since, $time = '+1 day')
You can also tell clients that you want them to cache responses. By using
Cake\Http\Response::withCache()
:
public function index()
{
// Enable caching
$this->response = $this->response->withCache('-1 minute', '+5 days');
}
The above would tell clients to cache the resulting response for 5 days,
hopefully speeding up your visitors’ experience.
The withCache()
method sets the Last-Modified
value to the first
argument. Expires
header and the max-age
directive are set based on the
second parameter. Cache-Control’s public
directive is set as well.
Fine Tuning HTTP Cache
One of the best and easiest ways of speeding up your application is to use HTTP
cache. Under this caching model, you are only required to help clients decide if
they should use a cached copy of the response by setting a few headers such as
modified time and response entity tag.
Rather than forcing you to code the logic for caching and for invalidating
(refreshing) it once the data has changed, HTTP uses two models, expiration and
validation, which usually are much simpler to use.
Apart from using Cake\Http\Response::withCache()
, you can also use
many other methods to fine-tune HTTP cache headers to take advantage of browser
or reverse proxy caching.
Sending Not-Modified Responses
-
Cake\Http\Response::isNotModified(Request $request)
Compares the cache headers for the request object with the cache header from the
response and determines whether it can still be considered fresh. If so, deletes
the response content, and sends the 304 Not Modified header:
// In a controller action.
if ($this->response->isNotModified($this->request)) {
return $this->response;
}
Setting Cookies
Cookies can be added to response using either an array or a Cake\Http\Cookie\Cookie
object:
use Cake\Http\Cookie\Cookie;
use DateTime;
// Add a cookie
$this->response = $this->response->withCookie(Cookie::create(
'remember_me',
'yes',
// All keys are optional
[
'expires' => new DateTime('+1 year'),
'path' => '',
'domain' => '',
'secure' => false,
'httponly' => false,
'samesite' => null // Or one of CookieInterface::SAMESITE_* constants
]
));
See the Creating Cookies section for how to use the cookie object. You
can use withExpiredCookie()
to send an expired cookie in the response. This
will make the browser remove its local cookie:
$this->response = $this->response->withExpiredCookie(new Cookie('remember_me'));
Running logic after the Response has been sent
In fastcgi based environments you can listen to the Server.terminate
event
to run logic after the response has been sent to the client. The
terminate
event will be passed a request
and response
. The
request
is fetched from the applications’ DI container, or from
Router::getRequest()
if the DI container does not have a request registered.
Warning
In non fastcgi environments the Server.terminate
event is fired before
the response is sent.