FastSitePHP\Web\Response

The Response Class represents an HTTP response and can be used to build and send the response.

源代码

GitHub

示例代码

Response - Content, Status Codes, Headers, Cookies, and Files

// By default when a string is returned in a route the server returns an
// HTML response. Without creating a Response Object, the Application Object
// can be used to specify a different 'Content-Type' Header which is what
// Browsers and HTTP Clients use to determine how to handle the response.
$app->get('/app-text-response', function() use ($app) {
    $app->header('Content-Type', 'text/plain');
    return 'Response using the Application Object';
});

// When using the Response Object [contentType()] and [content()]
// are the main functions to specify different content types.
$app->get('/text-response', function() {
    $res = new \FastSitePHP\Web\Response();
    return $res->contentType('text')->content('Text Response');
});

// When using the Response Object, properties are set through getter/setter
// functions and are chainable so they can be used on one line as shown
// above or seperated to multiple lines as shown here.
$app->get('/text-response2', function() {
    return (new \FastSitePHP\Web\Response())
        ->contentType('text')
        ->content('Text Response 2');
});

// Using the Response Object
$res = new \FastSitePHP\Web\Response();

// Set the 'Content-Type' Header.
// The following 3 function calls all set the same value.
// The difference is that [contentType()] is a helper function which allows
// for short-hand values of [html, json, jsonp, text, css, javascript, xml].
$res->contentType('text');
$res->contentType('text/plain');
$res->header('Content-Type', 'text/plain');

// Set Content
// For most content types use a string when setting [content()].
$res->content('<h1>FastSitePHP</h1>');

// For JSON Content either Objects and Arrays are used
$object = [
    'title' => 'Demo',
    'number' => '123',
];

$res
    ->contentType('json')
    ->content($object);

// The helper [json()] function sets both [contentType()] and [content()]
$res->json($object);

// For formatted JSON set the option [JSON_PRETTY_PRINT] before sending
// the Response. By default [JSON_UNESCAPED_UNICODE] is used and JSON
// is minimized. Any constant used by [json_encode()] can be set here.
$app->json_options = (JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$res->jsonOptions(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

// Status Codes
// [$app] only supports [200, 201, 202, 204, 205, 404, and 500]
// and the Response Object allows and handles 304 Responses along
// with any other valid or custom status codes.
$app->statusCode(201);
$res->statusCode(500);

// A helper function [pageNotFound()] exists on the Application Object that
// can be used to send a 404 response along with default or custom 404 page.
$app->get('/document/:name', function($name) use ($app) {
    if ($name !== 'test') {
        return $app->pageNotFound();
    }
    return 'Test';
});

// Specify a file for the response; the file specified will be streamed to the
// client and sent in a memory efficient manner so this function can be called
// on very large files with minimal performance impact for the server.
$file_path = __FILE__;
$res->file($file_path);

// Include specific Mime-Type along with Headers for Caching.
// Another topic on this page covers caching in more detail.
$res->file($file_path, 'text', 'etag:md5', 'private');

// Example File Usage
$app->get('/view-source-code', function() {
    $file_path = __FILE__;
    $res = new \FastSitePHP\Web\Response();
    return $res->file($file_path, 'download');
});

// Convert a file name or file type to a mime-type.
//
// File extensions that map to a Mime type with the function are:
//     Text: htm, html, txt, css, csv, md, markdown, jsx
//     Image: jpg, jpeg, png, gif, webp, svg, ico
//     Application: js, json, xml, pdf, woff
//     Video: mp4, webm, ogv, flv
//     Audio: mp3, weba, ogg, m4a, aac
//
// If a file type is not associated with a mime-type then a file
// download type of 'application/octet-stream' will be returned.
$mime_type = $res->fileTypeToMimeType('video.mp4');
$mime_type = $res->fileTypeToMimeType('mp4');

// Set Response Headers and Cookies

// Using the Application Object
$app->header('X-API-Key', 'App_1234');
$app->cookie('X-API-Key', 'App_1234');

// Or using the Response Object
$res->header('X-API-Key', 'Res_1234');
$res->cookie('X-API-Key', 'Res_1234');

// When creating a Response Object the Application Object can be
// passed and all App settings from [statusCode(), cors(), noCache(), headers(),
// cookies(), and json_options] will be passed to the Response Object.
$res = new \FastSitePHP\Web\Response($app);

HTTP Redirects

// HTTP Requests can be redirected using either the App or Response Object.
// When using the App Object and calling [redirect()] the PHP script ends
// immediately however any events defined from [after()] will be called.
// If your site uses Server-side Unit Testing you may want to use the response
// object which behaves as a regular route and doesn’t end script execution.

// User makes this request
$app->get('/page1', function() use ($app) {
    $app->redirect('page3');
});

// Or User makes this request
$app->get('/page2', function() {
    $res = new \FastSitePHP\Web\Response();
    return $res->redirect('page3');
});

// User will then see this URL and Response
$app->get('/page3', function() {
    return 'page3';
});

// The default Response Status Code is [302 'Found'] (Temporary Redirect),
// and an optional 2nd parameter for both App and Response allow for
// additional redirect response status codes:
//   301  Moved Permanently
//   302  Found
//   303  See Other
//   307  Temporary Redirect
//   308  Permanent Redirect
$app->get('/old-page', function() use ($app) {
    $app->redirect('new-page', 301);
});

Response - Cache Headers and Client-Side Caching

// Examples below show how to use Response Headers to control how a Browser
// or HTTP Client caches a Page or Resource.

// Prevent a Browser or Client from Caching a Page or File.
// Both the Application and the Response Objects have a [noCache()] function.
// Calling these functions will send 3 Response Headers to the client:
//     Cache-Control: no-cache, no-store, must-revalidate
//     Pragma: no-cache
//     Expires: -1
$app->noCache();

$res = new \FastSitePHP\Web\Response();
$res->noCache();

// If using certain Response Headers the Response Object will send a 304
// "Not Modified" Response depending on the Request Headers. 304 Responses
// are used by Browsers and other Clients to re-use previously fetched resources
// from their cached copy. This allows the user to see static resources more
// quickly and reduces the amount of traffic sent from the server.

// 'Cache-Control' Response Header. This header has different options to tell
// clients how they can cache a page. In this example only end users and not
// proxy servers can cache the response and they must re-validate it each time.
$res->cacheControl('private, must-revalidate');

// 'Expires' Response Header. This header is used to tell a client how long the
// content is valid for, however depending on 'Cache-Control' options this value
// may be ignored. Setting this value though does not trigger a 304 response and
// it's up to the browser or client how to handle it.
$res->expires('+1 month');

// 'ETag' Response Header (ETag is short for Entity Tag). An ETag represents a
// unique value for the content (often using a Hash). Browsers and Clients will
// send back an 'If-None-Match' Request Header with the version that they have
// cached and if it matches then the Response Object will send a 304 Response
// without the content since the browser can use the local copy.
$res->etag('hash:md5');

// The [etag()] function also accepts the hash itself or a closure function.
$res->etag('0132456789abcdef');
$res->etag(function($content) {
    return sha256($content);
});

// The optional 2nd parameter accepts the ETag Type of either 'strong' or 'weak'.
// The default is 'weak' and that is recommended to avoid complex caching errors.
// If you need to use 'strong' ETags you would likey want to do extra testing.
$res->etag('hash:sha256', 'weak');

// 'Last-Modified' Response Header. If set and if the client sends back an
// 'If-Modified-Since' Request Header that matches then a 304 Response will
// be sent. When setting the value use a Unix Timestamp or String that can be
// parsed by the PHP Function [strtotime()].
$res->lastModified('2019-01-01 13:01:30');

// 'Vary' Response Header. The 'Vary' Response Header can be used to
// specify rules for HTTP Caching and also to provide content hints to
// Google and other Search Engines.
$res->vary('User-Agent, Referer');

// When sending a file as the response you can specify optional parameters
// [$cache_type and $cache_control]. Cache Type has 3 valid options shown
// below and Cache Control sets the [cacheControl()] function.
$file_path = __FILE__;
$content_type = 'text';
$res->file($file_path, $content_type, 'etag:md5');
$res->file($file_path, $content_type, 'etag:sha1',     'private');
$res->file($file_path, $content_type, 'last-modified', 'public');

// When sending etags with [file()] and using either 'etag:md5' or 'etag:sha1'
// the hash is calculated each time. If you use ETags and have large files
// or frequently accessed files it would be a good idea to save the hash
// when the file is first created and set it through the [etag()] function.
$saved_hash = '0132456789abcdef';
$res->file($file_path)->etag($saved_hash);

Cross-Origin Resource Sharing (CORS)

// CORS is commonly used in Web API's to share data from one site or
// domain with another domain (cross-orign resource). To include the
// 'Access-Control-Allow-Origin' Header in your response use the [cors()]
// function. First make sure to set CORS headers from the App Object.
$app->cors('*');

// If using the Response Object either pass the App Object to either
// the Response when it's created or it's [cors()] function.
$res = new \FastSitePHP\Web\Response($app);
$res->cors($app);

// When passing a string the 'Access-Control-Allow-Origin' is validated
// and set, however if you need to pass additional CORS use an array
// with the named headers instead.
$app->cors([
    'Access-Control-Allow-Origin' => 'https://www.example.com',
    'Access-Control-Allow-Headers' => 'Authorization, Content-Type',
    'Access-Control-Allow-Credentials' => 'true',
    'Access-Control-Max-Age' => 86400,
]);

// If calling a POST, PUT, DELETE or other Request Method you may need
// to handle OPTIONS requests. When using CORS and an OPTIONS request is
// processed, FastSitePHP will automatically set the header
// 'Access-Control-Allow-Methods' based on how routes are defined.
// To make sure OPTIONS requests are handled first create a function
// that sets the CORS value.
$cors = function () use ($app) {
    $app->cors('*');
};

// Assign the Filter Function to the routes that use CORS:
$app->post('/api-data', function() {
    return [ 'example' => 'POST' ];
})
->filter($cors);

$app->put('/api-data', function() {
    return [ 'example' => 'PUT' ];
})
->filter($cors);

// If you do not want to allow FastSitePHP to handle OPTIONS
// requests you can turn it off using this option:
$app->allow_options_requests = false;

方法

__construct(Application $app = null)

Class Constructor

The FastSitePHP Application can be passed as an optional parameter and when used the Status Code and any Response Headers defined from the Application Object will be assigned to the Response Object.

header($name, $value = null)

Getter / Setter属性

Define an HTTP Header to be sent with the Response. Additionally previously defined Header fields can be read and cleared using this function. To set a Header field specify both $name and $value parameters. To read the value of a Header field specify only the $name parameter; if the value has been defined it will be returned otherwise if it has not been defined then null will be returned. To clear a Header field pass an empty string '' for the $value parameter. If setting or clearing a Header field then the Response Object will be returned so it can be called as a chainable method.

The Class [\FastSitePHP\Application] also has this function defined. The difference is that Application version is used for basic responses and headers are not validated.

Examples:
    Set the Response Header 'Content-Type' to 'text/plain'
    $res->header('Content-Type', 'text/plain')

    Get the Response Header 'Content-Type' that has been set.
    If no value has been set then null will be returned.
    $value = $res->header('Content-Type')

    Clear the Response Header 'Content-Type' that has been set
    $res->header('Content-Type', '')

返回类型: $this | mixed | null

headers()

Return an array of Headers fields defined from the header() function that will be or have been sent with the HTTP Response.

返回类型: array

statusCode($new_value = null)

Getter / Setter属性

Get or set the response status code by number (for example 200 for 'OK' or 404 for 'Not Found'). By default the PHP will set a status of 200 so setting a status code is usually only needed for other status codes other than 200. This gets sent when the response is sent to the client. If this function is called without a status code passed as a parameter then it will return the current status code otherwise when setting a status code it will return the Response object so it can be used in chainable methods.

返回类型: null | int | $this

contentType($type = null, $option = null)

Getter / Setter属性

Get or set the response content type header. This function is designed for developer ease of use so rather than having to define the full header such as 'Content-Type: application/json' the type 'json' can simply be used. The header is sent in the response from the function send(). This function supports the most common text content types used in web sites and web applications. For a full list of content media types see the defined standards from Internet Assigned Numbers Authority (IANA) in the reference link below.

If this function is called without a type passed as a a parameter then it will return the current content type otherwise it will return the Response object so it can be used in chainable methods.

Parameters: [$type] If specified will be one of 'html|json|jsonp|text|css|javascript|xml|graphql',
    any type from function [Response->fileTypeToMimeType()],
    or the actual content type for example 'text/html'. [$option] If $type is in 'html|css|javascript|text' then $option can be a string
    to specify the charset (e.g.: 'UTF-8') otherwise if 'jsonp' is the content type
    then $option can be a string or an array of query string parameters.
    By default if $option is null and the type is 'html' then 'UTF-8' is used
    as the charset and if the type is 'jsonp' and then the query string
    parameters 'callback' and 'jsonp' are used as the default.

返回类型: $this | mixed | null

jsonpQueryString($value = null)

Getter / Setter属性

Gets or sets the value of the Query String Parameters that would be used for a JSONP Request (JSON with Padding). This function would not commonly be used and instead simply calling contentType('jsonp') would be enough for most apps. The only time this function would likely be used is if the contentType() was manually set with a specific JavaScript character set then this function could be used to set the Query String Parameters.

返回类型: $this | array | null | string

content($content = null)

Getter / Setter属性

Get or set content that will be sent to the client. When a Route returns a Response Object the function [send()] will be called which sends the actual Response. To get the content of the response object call this function without any parameters and to specify content specify the [$content] parameter. If the response type [define from contentType()] is JSON or JSONP then the [$content] can be an array or object otherwise it should be a string. When setting a content value the Response Object Instance is returned.

Examples:

    $app->get('/html', function() {
        $res = new \FastSitePHP\Web\Response();
        return $res->content('<h1>FastSitePHP</h1>');
    });

    $app->get('/json', function() {
        $res = new \FastSitePHP\Web\Response();
        return $res
            ->contentType('json')
            ->content(array('Name' => 'FastSitePHP'));
    });

返回类型: $this | mixed

json($content)

Prepare the Response Object for a JSON Response with Content. This is a helper function to provide a shorter syntax for the following:

    $res->contentType('json')->content($object);

This is a setter function only and returns the Response Object. For practical usage a basic JSON response can be returned from the Application Object by simply returning an array to the route. In most cases this would be used along with other Response fields, for example:

    $res->header('API-Key', '123')->etag('hash:md5')->json($data);

返回类型: $this

jsonOptions($new_value = null)

Getter / Setter属性

Get or set options for [json_encode()] when a JSON Response is returned. Defaults to [JSON_UNESCAPED_UNICODE] when using PHP 5.4 or later.

Example:
    $res->jsonOptions(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

返回类型: int | $this

etag($value = null, $type = 'weak')

Getter / Setter属性

Get or set a value for the 'ETag' Response Header which is used to specify rules for HTTP Caching. ETag is short for Entity Tag and is typically a hash value (e.g.: md5 value of the content). When the function sendResponse() in this class gets called the ETag value is compared to the Request Header 'If-None-Match' and based on matching rules either a 200 'Ok' or 304 'Not Modified' response is returned for most webpages. There are two types of ETags validators: 'strong' and 'weak'.  A strong ETag is used to indicate that the contents of two requested resources including header fields at a URL (e.g.: webpages) are byte-for-byte identical. A weak ETag indicates that two requested resources are semantically equivalent. Strong ETags are not suitable for gzipped content because with compression turned on the response is not byte-for-byte identical. Depending upon the web server version if using strong ETags with gzipped content Nginx will remove them from the Response or convert them to weak ETags and Apache using mod_deflate will add a suffix which makes it unusable to most server side frameworks. Because of this weak ETags are used as the default option. If your site is using ETags then the Unit Testing Pages and the Samples Cache Test Section can be used to make sure that caching for your site is working as expected.

返回类型: $this | mixed | null

lastModified($last_modified_time = null)

Getter / Setter属性

Get or set a value for the 'Last-Modified' Response Header which is used to specify rules for HTTP Caching. Additionally when sendResponse() gets called the 'Last-Modified' value is compared to the Request Header 'If-Modified-Since' and based on matching rules either a 200 'Ok' or 304 'Not Modified' response is returned. If setting the value then the parameter value $ last_modified_time needs to be defined as an int to represent a Unix Timestamp or a valid string format for the php function strtotime().

返回类型: $this | mixed | null

cacheControl($value = null)

Getter / Setter属性

Get or set a value for the 'Cache-Control' Response Header which is used to specify rules for HTTP Caching. When setting the header value this function validates that it is in a correct format for defined HTTP 1.1 directive options and values. Per HTTP 1.1 Specs user defined fields are allowed however they are not commonly used so this function validates only for standards fields. This function is handled this way so that if there is a typo it can be caught. If the a custom 'Cache-Control' field name is needed then it can be added with the header() function instead.

返回类型: $this | mixed | null

expires($expires_time = null)

Getter / Setter属性

Get or set a value for the 'Expires' Response Header which is used to specify rules for HTTP Caching. If setting the value then the parameter value $expires_time needs to be defined as an int to represent a Unix Timestamp, string values of '0' or '-1' for to prevent caching, or a valid string format for the php function strtotime(). When setting the header value through this function the largest date allowed is one year from today. To set the header value to a date greater than one year from today use the header() function instead.

返回类型: $this | mixed | null

vary($value = null)

Getter / Setter属性

Get or set a value for the 'Vary' Response Header which is used to specify rules for HTTP Caching and also to provide content hints to Google and other Search Engines. When setting the header value this function validates that the options specified are valid options; this includes all server driven content negotiation headers and several commonly used request headers. It's possible that other options could be used and would be valid however this function validates for common options so that if there is a typo it can be caught and to catch logic errors with the parameters. The valid parameters that can be used with this function are ['Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'User-Agent', 'Origin', 'Cookie', and 'Referer']. If the a custom 'Vary' option is needed then it can be added with the header() function instead. Additionally testing should be performed when using this function because depending upon how the actual web server is configured this function could overwrite the web server value or the web server could overwrite the value set from this function.

返回类型: $this | mixed | null

noCache()

Getter / Setter属性

Set Response Headers that tell the browser or client to not cache the response.

This function defines the following response headers:
    Cache-Control: no-cache, no-store, must-revalidate
    Pragma: no-cache
    Expires: -1

For most clients and all modern browsers 'Cache-Control' will take precedence over 'Expires' when both tags exist. The 'Expires' header per HTTP Specs must be defined as an HTTP-Date value, and when an invalid value such as '0' is used then the client should treat the content as already expired, however in reality certain older versions of Internet Explorer may end up caching the response if '0' is used so '-1' is used for the 'Expires' header. At the time of writing both Google and Microsoft use 'Expires: -1' for their homepages. The header 'Pragma' is for old HTTP 1.0 clients that do not support either 'Cache-Control' or 'Expires'.

This function exists in both [FastSitePHP\Application] and [FastSitePHP\Web\Response] classes; calling the function from the Application object specifies the headers only when a route returns a basic response and calling the function from the Response object specifies the headers only when the route returns a Response object.

返回类型: $this | mixed

cors(Application $app = null)

Getter / Setter属性

Get or set a values for Cross-Origin Resource Sharing (CORS) Response Headers. For security reasons browsers will restrict content that is from a different domain when using JavaScript (for example: calling a Web Service from XMLHttpRequest). CORS is a web standard that allows for restricted resources to work on domains other than the domain where the resource is hosted.

CORS Headers are sent with both the OPTIONS request method and the calling method. Because OPTIONS requests are required for certain response types CORS Headers are initially defined from the Application Object and then passed the Response Object.

For more on this topic refer to documentation from the cors() function in the Application Object.

Example:
    $app->cors(array(
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Authorization',
    ));
    $res = new \FastSitePHP\Web\Response();
    $res->cors($app);

返回类型: $this | array | null

Define a cookie to be sent with the response along with the response headers. Internally this calls the PHP function setcookie() from the private function sendResponse(). To delete a cookie use the function [clearCookie()]. To read cookies use the [cookie()] function of the [FastSitePHP\Web\Request] Object or use the PHP superglobal array $_COOKIE.

The [$expire] parameter defaults to 0 which makes the cookie expire at the end of the session. Additionally if PHP 7.3 or higher is used then an array of [$options] can be used as the [$expire] parameter and no other parameters are required. [$options] allows for the `SameSite` Attribute.

返回类型: $this

clearCookie($name, $path_or_options = '', $domain = '', $secure = false, $httponly = false)

Send an empty value for a named cookie and expired time to tell the browser or client to clear the cookie.

返回类型: $this

signedCookie($name, $value = '', $expire_time = '+1 hour', $expire = 0, $path = '', $domain = '', $secure = false, $httponly = false)

Create a secure cookie that can be read by clients client but not tampered with. Cookies sent using this method need to be read with [Request->verifiedCookie()] to verify that they are not tampered with or expired. The default expiration time is 1 hour and it applies to the signed data and not the cookie itself.

Using this function requires the Application Config Value 'SIGNING_KEY'.

See also [encryptedCookie()] and [jwtCookie()].

返回类型: $this

jwtCookie($name, $value, $expire_time = '+1 hour', $expire = 0, $path = '', $domain = '', $secure = false, $httponly = false)

Create a secure cookie with a JSON Web Token (JWT). Cookies sent using this method need to be read with [Request->jwtCookie()] to verify that they are not tampered with or expired. The default expiration time is 1 hour and it applies to the JWT and not the cookie itself.

Using this function requires the Application Config Value 'JWT_KEY'.

See also [encryptedCookie()] and [signedCookie()].

返回类型: $this

encryptedCookie($name, $value = '', $expire = 0, $path = '', $domain = '', $secure = false, $httponly = false)

Create a secure and secret cookie that cannot be read by clients. Cookies sent using this method need to be read with [Request->decryptedCookie()].

Using this function requires the Application Config Value 'ENCRYPTION_KEY'.

See also [signedCookie()] and [jwtCookie()].

返回类型: $this

cookies()

Return the Array of Cookies that will be sent with the response.

返回类型: array

fileTypeToMimeType($file_name)

Return a Response Mime-type for a File extension for commonly used file formats in modern web apps and supported by popular browsers. For example 'file.txt' will return 'text/plain' and 'file.mp4' will return 'video/mp4'. The file path does not need to be a real file when calling this function. If a file type is not associated with a mime-type then 'application/octet-stream' will be returned indicating that the type of file is a file download; this includes common file types such as Office Documents and Windows BMP Images. For a large list of known Mime-types refer to the reference links below.

File extensions that map to a Mime type with the function are:
    Text: htm, html, txt, css, csv, md, markdown, jsx
    Image: jpg, jpeg, png, gif, webp, svg, ico
    Application: js, json, xml, pdf, woff, graphql
    Video: mp4, webm, ogv, flv
    Audio: mp3, weba, ogg, m4a, aac

返回类型: string

file($file_path = null, $content_type = null, $cache_type = null, $cache_control = null)

Getter / Setter属性

Specify a file for the response; the file specified will be streamed to the client and sent in a memory efficient manner so this function can be called on very large files with minimal performance impact for the server. The contents of the file are not modified when calling this function so it cannot be used to render templates. This function is ideal for sending file download responses and media files such as images or video.

This function provides several optional parameters to specify the response content type and caching headers:

$content_type The content type to set for contentType() such as 'text', 'html' or 'download' to specify 'application/octet-stream' and related headers for a file download. If not set then the mime type is determined from the file extension using the function fileTypeToMimeType().

$cache_type Value to set for either ETag or Last-Modified headers which allow for Cached Responses of 304 'Not Modified'. Valid options are: 'etag:md5', 'etag:sha1', and 'last-modified'. All values are calculated from the file directly. When calculating Etag based on a hash be aware that the value will be calculated each time this function is called so in the case of large files that are 100's of megabytes or more in size it can delay the initial streamed response by as much as a few seconds. If very large files are used with this function and ETag is needed then an alternative solution such as saving a hash of the file and setting it through the etag() function can be used to improve performance.

$cache_control Value for the 'Cache-Control' header which gets set from the function cacheControl().

返回类型: $this | string | null

redirect($url, $status_code = 302)

Specify a redirect URL for the response. By calling this function the response will redirect the user to another page or site by sending a status code of 3## for the response with the Location Header set to the new URL.

The redirect() function also exists in the main Application Object but can be used here instead if your site is designed to return a Response object for all routes.

Status Code can optionally be specified as the 2nd parameter. The default Status Code used is [302 'Found'] (Temporary Redirect). If Status Code [301 'Moved Permanently'] is used Web Browsers will typically cache the result so careful testing and consideration should be done if using a Status Code of 301. Other supported Status Codes are: [303 'See Other'], [307 'Temporary Redirect'], and [308 'Permanent Redirect'].

Example:

    // User makes this request
    $app->get('/page1', function() {
        $res = new \FastSitePHP\Web\Response();
        return $res->redirect('page2');
    });

    // User will then see this URL and Response
    $app->get('/page2', function() {
        return 'page2';
    });

返回类型: $this

reset()

Reset the Response object to its default state as if it were just created.

返回类型: $this

send()

Send the Response to the Client. This function gets called automatically if a route returns a response object and would normally not be manually called. This function handles sending Response Headers, Cookies, and Content.