CodeIgniter v4.5 API

DownloadResponse extends Response
in package

HTTP response when a download is requested.

Tags
see
DownloadResponseTest

Table of Contents

Properties

$body  : string|null
Message body
$bodyFormat  : string
Type of format the body is in.
$cookieStore  : CookieStore
CookieStore instance.
$CSP  : ContentSecurityPolicy
Content security policy handler
$headerMap  : array<string|int, mixed>
Holds a map of lower-case header names and their normal-case key as it is in $headers.
$headers  : array<string, Header|array<int, Header>>
List of all HTTP request headers.
$protocolVersion  : string
Protocol version
$reason  : string
Download reason
$statusCode  : int
The current status code for this response.
$statusCodes  : array<string|int, mixed>
HTTP status codes
$validProtocolVersions  : array<string|int, mixed>
List of valid protocol versions
$binary  : string|null
Download for binary
$charset  : string
Download charset
$file  : File|null
Download for file
$filename  : string
Download file name
$setMime  : bool
mime set flag

Methods

__construct()  : mixed
Constructor.
addHeader()  : $this
Adds a header (not a header value) with the same name.
appendBody()  : $this
Appends data to the body of the current message.
appendHeader()  : $this
Adds an additional header value to any headers that accept multiple values (i.e. are an array or implement ArrayAccess)
buildHeaders()  : void
set header for file download.
deleteCookie()  : $this
Sets a cookie to be deleted when the response is sent.
download()  : DownloadResponse|null
Force a download.
getBody()  : string|null
Returns the Message's body.
getContentLength()  : int
get content length.
getCookie()  : array<string, Cookie>|Cookie|null
Returns the cookie
getCookies()  : array<string, Cookie>
Returns all cookies currently set.
getCookieStore()  : CookieStore
Returns the `CookieStore` instance.
getCSP()  : ContentSecurityPolicy
getHeader()  : array<string|int, mixed>|Header|null
Returns a single header object. If multiple headers with the same name exist, then will return an array of header objects.
getHeaderLine()  : string
Retrieves a comma-separated string of the values for a single header.
getHeaders()  : array<string, Header>
Returns an array containing all headers.
getJSON()  : string|null
Returns the current body, converted to JSON is it isn't already.
getProtocolVersion()  : string
Returns the HTTP Protocol Version.
getReason()  : string
Gets the response response phrase associated with the status code.
getReasonPhrase()  : string
Gets the response reason phrase associated with the status code.
getStatusCode()  : int
Gets the response status code.
getXML()  : bool|string|null
Retrieves the current body into XML and returns it.
hasCookie()  : bool
Checks to see if the Response has a specified cookie or not.
hasHeader()  : bool
Determines whether a header exists.
header()  : Header|array<int, Header>|null
Returns a single Header object. If multiple headers with the same name exist, then will return an array of header objects.
headers()  : array<string, Header|array<int, Header>>
Returns an array containing all Headers.
inline()  : DownloadResponse
Sets the response header to display the file in the browser.
noCache()  : $this
Sets the appropriate headers to ensure this response is not cached by the browsers.
populateHeaders()  : void
Populates the $headers array with any headers the server knows about.
prependHeader()  : $this
Adds an additional header value to any headers that accept multiple values (i.e. are an array or implement ArrayAccess)
redirect()  : $this
Perform a redirect to a new URL, in two flavors: header or location.
removeHeader()  : $this
Removes a header from the list of headers we track.
send()  : $this
Sends the output to the browser.
sendBody()  : DownloadResponse
output download file text.
sendHeaders()  : $this
Sends the headers of this HTTP response to the browser.
setBinary()  : void
set download for binary string.
setBody()  : $this
Sets the body of the current message.
setCache()  : $this
A shortcut method that allows the developer to set all of the cache-control headers in one method call.
setContentType()  : ResponseInterface
Sets the Content Type header for this response with the mime type and, optionally, the charset.
setCookie()  : $this
Set a cookie
setDate()  : $this
Sets the date header
setFileName()  : $this
set name for the download.
setFilePath()  : void
set download for file.
setHeader()  : $this
Sets a header and it's value.
setJSON()  : $this
Converts the $body into JSON and sets the Content Type header.
setLastModified()  : $this
Sets the Last-Modified date header.
setLink()  : $this
Set the Link Header
setProtocolVersion()  : $this
Sets the HTTP protocol version.
setStatusCode()  : $this
Disallows status changing.
setXML()  : $this
Converts $body into XML, and sets the correct Content-Type.
formatBody()  : false|string
Handles conversion of the data into the appropriate format, and sets the correct Content-Type header for our response.
getHeaderName()  : string
Takes a header name in any case, and returns the normal-case version of the header.
sendCookies()  : void
Actually sets the cookies.
checkMultipleHeaders()  : void
dispatchCookies()  : void
doSetCookie()  : void
Extracted call to `setcookie()` in order to run unit tests on it.
doSetRawCookie()  : void
Extracted call to `setrawcookie()` in order to run unit tests on it.
getContentDisposition()  : string
get Content-Disposition Header string.
getDownloadFileName()  : string
get download filename.
hasMultipleHeaders()  : bool
sendBodyByBinary()  : DownloadResponse
output download text by binary
sendBodyByFilePath()  : DownloadResponse
output download text by file.
setContentTypeByMimeType()  : void
Set content type by guessing mime type from file extension

Properties

$body

Message body

protected string|null $body

$bodyFormat

Type of format the body is in.

protected string $bodyFormat = 'html'

Valid: html, json, xml

$headerMap

Holds a map of lower-case header names and their normal-case key as it is in $headers.

protected array<string|int, mixed> $headerMap = []

Used for case-insensitive header access.

$headers

List of all HTTP request headers.

protected array<string, Header|array<int, Header>> $headers = []

[name => Header] or [name => [Header1, Header2]]

$protocolVersion

Protocol version

protected string $protocolVersion

$statusCode

The current status code for this response.

protected int $statusCode = 200

$statusCodes

HTTP status codes

protected static array<string|int, mixed> $statusCodes = [ // 1xx: Informational 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', // http://www.iana.org/go/rfc2518 103 => 'Early Hints', // http://www.ietf.org/rfc/rfc8297.txt // 2xx: Success 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', // 1.1 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', // http://www.iana.org/go/rfc4918 208 => 'Already Reported', // http://www.iana.org/go/rfc5842 226 => 'IM Used', // 1.1; http://www.ietf.org/rfc/rfc3229.txt // 3xx: Redirection 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', // Formerly 'Moved Temporarily' 303 => 'See Other', // 1.1 304 => 'Not Modified', 305 => 'Use Proxy', // 1.1 306 => 'Switch Proxy', // No longer used 307 => 'Temporary Redirect', // 1.1 308 => 'Permanent Redirect', // 1.1; Experimental; http://www.ietf.org/rfc/rfc7238.txt // 4xx: Client error 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Content Too Large', // https://www.iana.org/assignments/http-status-codes/http-status-codes.xml 414 => 'URI Too Long', // https://www.iana.org/assignments/http-status-codes/http-status-codes.xml 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 418 => "I'm a teapot", // April's Fools joke; http://www.ietf.org/rfc/rfc2324.txt // 419 (Authentication Timeout) is a non-standard status code with unknown origin 421 => 'Misdirected Request', // http://www.iana.org/go/rfc7540 Section 9.1.2 422 => 'Unprocessable Content', // https://www.iana.org/assignments/http-status-codes/http-status-codes.xml 423 => 'Locked', // http://www.iana.org/go/rfc4918 424 => 'Failed Dependency', // http://www.iana.org/go/rfc4918 425 => 'Too Early', // https://datatracker.ietf.org/doc/draft-ietf-httpbis-replay/ 426 => 'Upgrade Required', 428 => 'Precondition Required', // 1.1; http://www.ietf.org/rfc/rfc6585.txt 429 => 'Too Many Requests', // 1.1; http://www.ietf.org/rfc/rfc6585.txt 431 => 'Request Header Fields Too Large', // 1.1; http://www.ietf.org/rfc/rfc6585.txt 451 => 'Unavailable For Legal Reasons', // http://tools.ietf.org/html/rfc7725 499 => 'Client Closed Request', // http://lxr.nginx.org/source/src/http/ngx_http_request.h#0133 // 5xx: Server error 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates', // 1.1; http://www.ietf.org/rfc/rfc2295.txt 507 => 'Insufficient Storage', // http://www.iana.org/go/rfc4918 508 => 'Loop Detected', // http://www.iana.org/go/rfc5842 510 => 'Not Extended', // http://www.ietf.org/rfc/rfc2774.txt 511 => 'Network Authentication Required', // http://www.ietf.org/rfc/rfc6585.txt 599 => 'Network Connect Timeout Error', ]

$validProtocolVersions

List of valid protocol versions

protected array<string|int, mixed> $validProtocolVersions = ['1.0', '1.1', '2.0', '3.0']

Methods

__construct()

Constructor.

public __construct(string $filename, bool $setMime) : mixed
Parameters
$filename : string
$setMime : bool

addHeader()

Adds a header (not a header value) with the same name.

public addHeader(string $name, string $value) : $this

Use this only when you set multiple headers with the same name, typically, for Set-Cookie.

Parameters
$name : string
$value : string
Return values
$this

appendBody()

Appends data to the body of the current message.

public appendBody(string $data) : $this
Parameters
$data : string
Return values
$this

appendHeader()

Adds an additional header value to any headers that accept multiple values (i.e. are an array or implement ArrayAccess)

public appendHeader(string $name, string|null $value) : $this
Parameters
$name : string
$value : string|null
Return values
$this

buildHeaders()

set header for file download.

public buildHeaders() : void

deleteCookie()

Sets a cookie to be deleted when the response is sent.

public deleteCookie([string $name = '' ][, string $domain = '' ][, string $path = '/' ][, string $prefix = '' ]) : $this
Parameters
$name : string = ''
$domain : string = ''
$path : string = '/'
$prefix : string = ''
Return values
$this

download()

Force a download.

public download([string $filename = '' ][, string|null $data = '' ][, bool $setMime = false ]) : DownloadResponse|null

Generates the headers that force a download to happen. And sends the file to the browser.

Parameters
$filename : string = ''

The name you want the downloaded file to be named or the path to the file to send

$data : string|null = ''

The data to be downloaded. Set null if the $filename is the file path

$setMime : bool = false

Whether to try and send the actual MIME type

Return values
DownloadResponse|null

getBody()

Returns the Message's body.

public getBody() : string|null
Return values
string|null

getContentLength()

get content length.

public getContentLength() : int
Return values
int

getCookie()

Returns the cookie

public getCookie([string|null $name = null ][, string $prefix = '' ]) : array<string, Cookie>|Cookie|null
Parameters
$name : string|null = null
$prefix : string = ''

Cookie prefix. '': the default prefix

Return values
array<string, Cookie>|Cookie|null

getCookies()

Returns all cookies currently set.

public getCookies() : array<string, Cookie>
Return values
array<string, Cookie>

getHeader()

Returns a single header object. If multiple headers with the same name exist, then will return an array of header objects.

public getHeader(string $name) : array<string|int, mixed>|Header|null

Use Message::header() to make room for PSR-7

Parameters
$name : string
Tags
TODO

Incompatible return value with PSR-7

codeCoverageIgnore
Return values
array<string|int, mixed>|Header|null

getHeaderLine()

Retrieves a comma-separated string of the values for a single header.

public getHeaderLine(string $name) : string

This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.

NOTE: Not all header values may be appropriately represented using comma concatenation. For such headers, use getHeader() instead and supply your own delimiter when concatenating.

Parameters
$name : string
Return values
string

getHeaders()

Returns an array containing all headers.

public getHeaders() : array<string, Header>

Use Message::headers() to make room for PSR-7

Tags
TODO

Incompatible return value with PSR-7

codeCoverageIgnore
Return values
array<string, Header>

An array of the request headers

getJSON()

Returns the current body, converted to JSON is it isn't already.

public getJSON() : string|null
Tags
throws
InvalidArgumentException

If the body property is not array.

Return values
string|null

getProtocolVersion()

Returns the HTTP Protocol Version.

public getProtocolVersion() : string
Return values
string

HTTP protocol version.

getReasonPhrase()

Gets the response reason phrase associated with the status code.

public getReasonPhrase() : string

Because a reason phrase is not a required element in a response status line, the reason phrase value MAY be null. Implementations MAY choose to return the default RFC 7231 recommended reason phrase (or those listed in the IANA HTTP Status Code Registry) for the response's status code.

Tags
see
http://tools.ietf.org/html/rfc7231#section-6
see
http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
Return values
string

Reason phrase; must return an empty string if none present.

getStatusCode()

Gets the response status code.

public getStatusCode() : int

The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.

Return values
int

Status code.

getXML()

Retrieves the current body into XML and returns it.

public getXML() : bool|string|null
Tags
throws
InvalidArgumentException

If the body property is not array.

Return values
bool|string|null

hasCookie()

Checks to see if the Response has a specified cookie or not.

public hasCookie(string $name[, string|null $value = null ][, string $prefix = '' ]) : bool
Parameters
$name : string
$value : string|null = null
$prefix : string = ''
Return values
bool

hasHeader()

Determines whether a header exists.

public hasHeader(string $name) : bool
Parameters
$name : string

Case-insensitive header field name.

Return values
bool

Returns true if any header names match the given header name using a case-insensitive string comparison. Returns false if no matching header name is found in the message.

header()

Returns a single Header object. If multiple headers with the same name exist, then will return an array of header objects.

public header(string $name) : Header|array<int, Header>|null
Parameters
$name : string
Return values
Header|array<int, Header>|null

headers()

Returns an array containing all Headers.

public headers() : array<string, Header|array<int, Header>>
Return values
array<string, Header|array<int, Header>>

An array of the Header objects

noCache()

Sets the appropriate headers to ensure this response is not cached by the browsers.

public noCache() : $this
Return values
$this

populateHeaders()

Populates the $headers array with any headers the server knows about.

public populateHeaders() : void

prependHeader()

Adds an additional header value to any headers that accept multiple values (i.e. are an array or implement ArrayAccess)

public prependHeader(string $name, string $value) : $this
Parameters
$name : string
$value : string
Return values
$this

redirect()

Perform a redirect to a new URL, in two flavors: header or location.

public redirect(string $uri[, string $method = 'auto' ][, int|null $code = null ]) : $this
Parameters
$uri : string

The URI to redirect to

$method : string = 'auto'
$code : int|null = null

The type of redirection, defaults to 302

Tags
throws
HTTPException

For invalid status code.

Return values
$this

removeHeader()

Removes a header from the list of headers we track.

public removeHeader(string $name) : $this
Parameters
$name : string
Return values
$this

send()

Sends the output to the browser.

public send() : $this
Tags
todo

Do downloads need CSP or Cookies? Compare with ResponseTrait::send()

Return values
$this

sendHeaders()

Sends the headers of this HTTP response to the browser.

public sendHeaders() : $this
Return values
$this

setBinary()

set download for binary string.

public setBinary(string $binary) : void
Parameters
$binary : string

setBody()

Sets the body of the current message.

public setBody(string $data) : $this
Parameters
$data : string
Return values
$this

setCache()

A shortcut method that allows the developer to set all of the cache-control headers in one method call.

public setCache([array<string|int, mixed> $options = [] ]) : $this

The options array is used to provide the cache-control directives for the header. It might look something like:

 $options = [
     'max-age'  => 300,
     's-maxage' => 900
     'etag'     => 'abcde',
 ];

Typical options are:

  • etag
  • last-modified
  • max-age
  • s-maxage
  • private
  • public
  • must-revalidate
  • proxy-revalidate
  • no-transform
Parameters
$options : array<string|int, mixed> = []
Return values
$this

setContentType()

Sets the Content Type header for this response with the mime type and, optionally, the charset.

public setContentType(string $mime[, string $charset = 'UTF-8' ]) : ResponseInterface
Parameters
$mime : string
$charset : string = 'UTF-8'
Return values
ResponseInterface

setCookie()

Set a cookie

public setCookie(array<string|int, mixed>|Cookie|string $name[, string $value = '' ][, int $expire = 0 ][, string $domain = '' ][, string $path = '/' ][, string $prefix = '' ][, bool|null $secure = null ][, bool|null $httponly = null ][, string|null $samesite = null ]) : $this

Accepts an arbitrary number of binds (up to 7) or an associative array in the first parameter containing all the values.

Parameters
$name : array<string|int, mixed>|Cookie|string

Cookie name / array containing binds / Cookie object

$value : string = ''

Cookie value

$expire : int = 0

Cookie expiration time in seconds

$domain : string = ''

Cookie domain (e.g.: '.yourdomain.com')

$path : string = '/'

Cookie path (default: '/')

$prefix : string = ''

Cookie name prefix ('': the default prefix)

$secure : bool|null = null

Whether to only transfer cookies via SSL

$httponly : bool|null = null

Whether only make the cookie accessible via HTTP (no javascript)

$samesite : string|null = null
Return values
$this

setDate()

Sets the date header

public setDate(DateTime $date) : $this
Parameters
$date : DateTime
Return values
$this

setFileName()

set name for the download.

public setFileName(string $filename) : $this
Parameters
$filename : string
Return values
$this

setFilePath()

set download for file.

public setFilePath(string $filepath) : void
Parameters
$filepath : string

setHeader()

Sets a header and it's value.

public setHeader(string $name, array<string|int, mixed>|string|null $value) : $this
Parameters
$name : string
$value : array<string|int, mixed>|string|null
Return values
$this

setJSON()

Converts the $body into JSON and sets the Content Type header.

public setJSON(array<string|int, mixed>|object|string $body[, bool $unencoded = false ]) : $this
Parameters
$body : array<string|int, mixed>|object|string
$unencoded : bool = false
Return values
$this

setLastModified()

Sets the Last-Modified date header.

public setLastModified(DateTime|string $date) : $this

$date can be either a string representation of the date or, preferably, an instance of DateTime.

Parameters
$date : DateTime|string
Return values
$this

setProtocolVersion()

Sets the HTTP protocol version.

public setProtocolVersion(string $version) : $this
Parameters
$version : string
Tags
throws
HTTPException

For invalid protocols

Return values
$this

setStatusCode()

Disallows status changing.

public setStatusCode(int $code[, string $reason = '' ]) : $this
Parameters
$code : int

The 3-digit integer result code to set.

$reason : string = ''

The reason phrase to use with the provided status code; if none is provided, will default to the IANA name.

Tags
throws
DownloadException
Return values
$this

setXML()

Converts $body into XML, and sets the correct Content-Type.

public setXML(array<string|int, mixed>|string $body) : $this
Parameters
$body : array<string|int, mixed>|string
Return values
$this

formatBody()

Handles conversion of the data into the appropriate format, and sets the correct Content-Type header for our response.

protected formatBody(array<string|int, mixed>|object|string $body, string $format) : false|string
Parameters
$body : array<string|int, mixed>|object|string
$format : string

Valid: json, xml

Tags
throws
InvalidArgumentException

If the body property is not string or array.

Return values
false|string

getHeaderName()

Takes a header name in any case, and returns the normal-case version of the header.

protected getHeaderName(string $name) : string
Parameters
$name : string
Return values
string

sendCookies()

Actually sets the cookies.

protected sendCookies() : void

checkMultipleHeaders()

private checkMultipleHeaders(string $name) : void
Parameters
$name : string

doSetCookie()

Extracted call to `setcookie()` in order to run unit tests on it.

private doSetCookie(string $name, string $value, array<string|int, mixed> $options) : void
Parameters
$name : string
$value : string
$options : array<string|int, mixed>
Tags
codeCoverageIgnore

doSetRawCookie()

Extracted call to `setrawcookie()` in order to run unit tests on it.

private doSetRawCookie(string $name, string $value, array<string|int, mixed> $options) : void
Parameters
$name : string
$value : string
$options : array<string|int, mixed>
Tags
codeCoverageIgnore

getContentDisposition()

get Content-Disposition Header string.

private getContentDisposition() : string
Return values
string

getDownloadFileName()

get download filename.

private getDownloadFileName() : string
Return values
string

hasMultipleHeaders()

private hasMultipleHeaders(string $name) : bool
Parameters
$name : string
Return values
bool

setContentTypeByMimeType()

Set content type by guessing mime type from file extension

private setContentTypeByMimeType() : void

        
On this page

Search results