HTTP Responses

The Response class extends the HTTP Message Class with methods only appropriate fora server responding to the client that called it.

Working with the Response

A Response class is instantiated for you and passed into your controllers. It can be accessed through$this->response. Many times you will not need to touch the class directly, since CodeIgniter takes care ofsending the headers and the body for you. This is great if the page successfully created the content it was asked to.When things go wrong, or you need to send very specific status codes back, or even take advantage of thepowerful HTTP caching, it’s there for you.

Setting the Output

When you need to set the output of the script directly, and not rely on CodeIgniter to automatically get it, youdo it manually with the setBody method. This is usually used in conjunction with setting the status code ofthe response:

  1. $this->response->setStatusCode(404)
  2. ->setBody($body);

The reason phrase (‘OK’, ‘Created’, ‘Moved Permanently’) will be automatically added, but you can add custom reasonsas the second parameter of the setStatusCode() method:

  1. $this->response->setStatusCode(404, 'Nope. Not here.');

You can set format an array into either JSON or XML and set the content type header to the appropriate mime with thesetJSON and setXML methods. Typically, you will send an array of data to be converted:

  1. $data = [
  2. 'success' => true,
  3. 'id' => 123
  4. ];
  5.  
  6. return $this->response->setJSON($data);
  7. or
  8. return $this->response->setXML($data);

Setting Headers

Often, you will need to set headers to be set for the response. The Response class makes this very simple to do,with the setHeader() method. The first parameter is the name of the header. The second parameter is the value,which can be either a string or an array of values that will be combined correctly when sent to the client.Using these functions instead of using the native PHP functions allows you to ensure that no headers are sentprematurely, causing errors, and makes testing possible.

  1. $response->setHeader('Location', 'http://example.com')
  2. ->setHeader('WWW-Authenticate', 'Negotiate');

If the header exists and can have more than one value, you may use the appendHeader() and prependHeader()methods to add the value to the end or beginning of the values list, respectively. The first parameter is the nameof the header, while the second is the value to append or prepend.

  1. $response->setHeader('Cache-Control', 'no-cache')
  2. ->appendHeader('Cache-Control', 'must-revalidate');

Headers can be removed from the response with the removeHeader() method, which takes the header name as the onlyparameter. This is not case-sensitive.

  1. $response->removeHeader('Location');

Force File Download

The Response class provides a simple way to send a file to the client, prompting the browser to download the datato your computer. This sets the appropriate headers to make it happen.

The first parameter is the name you want the downloaded file to be named, the second parameter is thefile data.

If you set the second parameter to NULL and $filename is an existing, readablefile path, then its content will be read instead.

If you set the third parameter to boolean TRUE, then the actual file MIME type(based on the filename extension) will be sent, so that if your browser has ahandler for that type - it can use it.

Example:

  1. $data = 'Here is some text!';
  2. $name = 'mytext.txt';
  3. return $response->download($name, $data);

If you want to download an existing file from your server you’ll need todo the following:

  1. // Contents of photo.jpg will be automatically read
  2. return $response->download('/path/to/photo.jpg', NULL);

Use the optional setFileName() method to change the filename as it is sent to the client’s browser:

  1. return $response->download('awkwardEncryptedFileName.fakeExt')->setFileName('expenses.csv');

Note

The response object MUST be returned for the download to be sent to the client. This allows the responseto be passed through all after filters before being sent to the client.

HTTP Caching

Built into the HTTP specification are tools help the client (often the web browser) cache the results. Used correctly,this can lend a huge performance boost to your application because it will tell the client that they don’t needto contact the getServer at all since nothing has changed. And you can’t get faster than that.

This are handled through the Cache-Control and ETag headers. This guide is not the proper place for a thoroughintroduction to all of the cache headers power, but you can get a good understanding over atGoogle Developersand the Mobify Blog.

By default, all response objects sent through CodeIgniter have HTTP caching turned off. The options and exactcircumstances are too varied for us to be able to create a good default other than turning it off. It’s simpleto set the Cache values to what you need, though, through the setCache() method:

  1. $options = [
  2. 'max-age' => 300,
  3. 's-maxage' => 900
  4. 'etag' => 'abcde',
  5. ];
  6. $this->response->setCache($options);

The $options array simply takes an array of key/value pairs that are, with a couple of exceptions, assignedto the Cache-Control header. You are free to set all of the options exactly as you need for your specificsituation. While most of the options are applied to the Cache-Control header, it intelligently handlesthe etag and last-modified options to their appropriate header.

Content Security Policy

One of the best protections you have against XSS attacks is to implement a Content Security Policy on the site.This forces you to whitelist every single source of content that is pulled in from your site’s HTML,including images, stylesheets, javascript files, etc. The browser will refuse content from sources that don’t meetthe whitelist. This whitelist is created within the response’s Content-Security-Policy header and has manydifferent ways it can be configured.

This sounds complex, and on some sites, can definitely be challenging. For many simple sites, though, where all contentis served by the same domain (http://example.com), it is very simple to integrate.

As this is a complex subject, this user guide will not go over all of the details. For more information, you shouldvisit the following sites:

Turning CSP On

By default, support for this is off. To enable support in your application, edit the CSPEnabled value inapp/Config/App.php:

  1. public $CSPEnabled = true;

When enabled, the response object will contain an instance of CodeIgniter\HTTP\ContentSecurityPolicy. Thevalues set in app/Config/ContentSecurityPolicy.php are applied to that instance, and if no changes areneeded during runtime, then the correctly formatted header is sent and you’re all done.

With CSP enabled, two header lines are added to the HTTP response: a Content-Security-Policy header, withpolicies identifying content types or origins that are explicitly allowed for differentcontexts, and a Content-Security-Policy-Report-Only header, which identifies content typesor origins that will be allowed but which will also be reported to the destinationof your choice.

Our implementation provides for a default treatment, changeable through the reportOnly() method.When an additional entry is added to a CSP directive, as shown below, it will be addedto the CSP header appropriate for blocking or preventing. That can be overridden on a percall basis, by providing an optional second parameter to the adding method call.

Runtime Configuration

If your application needs to make changes at run-time, you can access the instance at $response->CSP. Theclass holds a number of methods that map pretty clearly to the appropriate header value that you need to set.Examples are shown below, with different combinations of parameters, though all accept either a directivename or anarray of them.:

  1. // specify the default directive treatment
  2. $response->CSP->reportOnly(false);
  3.  
  4. // specify the origin to use if none provided for a directive
  5. $response->CSP->setDefaultSrc('cdn.example.com');
  6. // specify the URL that "report-only" reports get sent to
  7. $response->CSP->setReportURI('http://example.com/csp/reports');
  8. // specify that HTTP requests be upgraded to HTTPS
  9. $response->CSP->upgradeInsecureRequests(true);
  10.  
  11. // add types or origins to CSP directives
  12. // assuming that the default treatment is to block rather than just report
  13. $response->CSP->addBaseURI('example.com', true); // report only
  14. $response->CSP->addChildSrc('https://youtube.com'); // blocked
  15. $response->CSP->addConnectSrc('https://*.facebook.com', false); // blocked
  16. $response->CSP->addFontSrc('fonts.example.com');
  17. $response->CSP->addFormAction('self');
  18. $response->CSP->addFrameAncestor('none', true); // report this one
  19. $response->CSP->addImageSrc('cdn.example.com');
  20. $response->CSP->addMediaSrc('cdn.example.com');
  21. $response->CSP->addManifestSrc('cdn.example.com');
  22. $response->CSP->addObjectSrc('cdn.example.com', false); // reject from here
  23. $response->CSP->addPluginType('application/pdf', false); // reject this media type
  24. $response->CSP->addScriptSrc('scripts.example.com', true); // allow but report requests from here
  25. $response->CSP->addStyleSrc('css.example.com');
  26. $response->CSP->addSandbox(['allow-forms', 'allow-scripts']);

The first parameter to each of the “add” methods is an appropriate string value,or an array of them.

The reportOnly method allows you to specify the default reporting treatmentfor subsequent sources, unless over-ridden. For instance, you could specifythat youtube.com was allowed, and then provide several allowed but reported sources:

  1. $response->addChildSrc('https://youtube.com'); // allowed
  2. $response->reportOnly(true);
  3. $response->addChildSrc('https://metube.com'); // allowed but reported
  4. $response->addChildSrc('https://ourtube.com',false); // allowed

Inline Content

It is possible to set a website to not protect even inline scripts and styles on its own pages, since this might havebeen the result of user-generated content. To protect against this, CSP allows you to specify a nonce within the<style> and <script> tags, and to add those values to the response’s header. This is a pain to handle in reallife, and is most secure when generated on the fly. To make this simple, you can include a {csp-style-nonce} or{csp-script-nonce} placeholder in the tag and it will be handled for you automatically:

  1. // Original
  2. <script {csp-script-nonce}>
  3. console.log("Script won't run as it doesn't contain a nonce attribute");
  4. </script>
  5.  
  6. // Becomes
  7. <script nonce="Eskdikejidojdk978Ad8jf">
  8. console.log("Script won't run as it doesn't contain a nonce attribute");
  9. </script>
  10.  
  11. // OR
  12. <style {csp-style-nonce}>
  13. . . .
  14. </style>

Class Reference

Note

In addition to the methods listed here, this class inherits the methods from theMessage Class.

The methods provided by the parent class that are available are:

  • CodeIgniter\HTTP\Message::body()
  • CodeIgniter\HTTP\Message::setBody()
  • CodeIgniter\HTTP\Message::populateHeaders()
  • CodeIgniter\HTTP\Message::headers()
  • CodeIgniter\HTTP\Message::header()
  • CodeIgniter\HTTP\Message::headerLine()
  • CodeIgniter\HTTP\Message::setHeader()
  • CodeIgniter\HTTP\Message::removeHeader()
  • CodeIgniter\HTTP\Message::appendHeader()
  • CodeIgniter\HTTP\Message::protocolVersion()
  • CodeIgniter\HTTP\Message::setProtocolVersion()
  • CodeIgniter\HTTP\Message::negotiateMedia()
  • CodeIgniter\HTTP\Message::negotiateCharset()
  • CodeIgniter\HTTP\Message::negotiateEncoding()
  • CodeIgniter\HTTP\Message::negotiateLanguage()
  • CodeIgniter\HTTP\Message::negotiateLanguage()
  • CodeIgniter\HTTP\Response
    • getStatusCode()

Returns:The current HTTP status code for this responseReturn type:int

Returns the currently status code for this response. If no status code has been set, a BadMethodCallExceptionwill be thrown:

  1. echo $response->getStatusCode();
  • setStatusCode($code[, $reason=''])

Parameters:

  1. - **$code** (_int_) The HTTP status code
  2. - **$reason** (_string_) An optional reason phrase.Returns:

The current Response instanceReturn type:CodeIgniter\HTTP\Response

Sets the HTTP status code that should be sent with this response:

  1. $response->setStatusCode(404);

The reason phrase will be automatically generated based upon the official lists. If you need to set your ownfor a custom status code, you can pass the reason phrase as the second parameter:

  1. $response->setStatusCode(230, "Tardis initiated");
  • getReason()

Returns:The current reason phrase.Return type:string

Returns the current status code for this response. If not status has been set, will return an empty string:

  1. echo $response->getReason();
  • setDate($date)

Parameters:

  1. - **$date** (_DateTime_) A DateTime instance with the time to set for this response.Returns:

The current response instance.Return type:CodeIgniterHTTPResponse

Sets the date used for this response. The $date argument must be an instance of DateTime:

  1. $date = DateTime::createFromFormat('j-M-Y', '15-Feb-2016');
  2. $response->setDate($date);
  • setContentType($mime[, $charset='UTF-8'])

Parameters:

  1. - **$mime** (_string_) The content type this response represents.
  2. - **$charset** (_string_) The character set this response uses.Returns:

The current response instance.Return type:CodeIgniterHTTPResponse

Sets the content type this response represents:

  1. $response->setContentType('text/plain');
  2. $response->setContentType('text/html');
  3. $response->setContentType('application/json');

By default, the method sets the character set to UTF-8. If you need to change this, you canpass the character set as the second parameter:

  1. $response->setContentType('text/plain', 'x-pig-latin');
  • noCache()

Returns:The current response instance.Return type:CodeIgniterHTTPResponse

Sets the Cache-Control header to turn off all HTTP caching. This is the default settingof all response messages:

  1. $response->noCache();
  2.  
  3. // Sets the following header:
  4. Cache-Control: no-store, max-age=0, no-cache
  • setCache($options)

Parameters:

  1. - **$options** (_array_) An array of key/value cache control settingsReturns:

The current response instance.Return type:CodeIgniterHTTPResponse

Sets the Cache-Control headers, including ETags and Last-Modified. Typical keys are:

  1. - etag
  2. - last-modified
  3. - max-age
  4. - s-maxage
  5. - private
  6. - public
  7. - must-revalidate
  8. - proxy-revalidate
  9. - no-transform

When passing the last-modified option, it can be either a date string, or a DateTime object.

  • setLastModified($date)

Parameters:

  1. - **$date** (_string|DateTime_) The date to set the Last-Modified header toReturns:

The current response instance.Return type:CodeIgniterHTTPResponse

Sets the Last-Modified header. The $date object can be either a string or a DateTimeinstance:

  1. $response->setLastModified(date('D, d M Y H:i:s'));
  2. $response->setLastModified(DateTime::createFromFormat('u', $time));
  • send()

Returns:The current response instance.Return type:CodeIgniterHTTPResponse

Tells the response to send everything back to the client. This will first send the headers,followed by the response body. For the main application response, you do not need to callthis as it is handled automatically by CodeIgniter.

  • setCookie($name = ''[, $value = ''[, $expire = ''[, $domain = ''[, $path = '/'[, $prefix = ''[, $secure = FALSE[, $httponly = FALSE]]]]]]])

Parameters:

  1. - **$name** (_mixed_) Cookie name or an array of parameters
  2. - **$value** (_string_) Cookie value
  3. - **$expire** (_int_) Cookie expiration time in seconds
  4. - **$domain** (_string_) Cookie domain
  5. - **$path** (_string_) Cookie path
  6. - **$prefix** (_string_) Cookie name prefix
  7. - **$secure** (_bool_) Whether to only transfer the cookie through HTTPS
  8. - **$httponly** (_bool_) Whether to only make the cookie accessible for HTTP requests (no JavaScript)Return type:

void

Sets a cookie containing the values you specify. There are two ways topass information to this method so that a cookie can be set: ArrayMethod, and Discrete Parameters:

Array Method

Using this method, an associative array is passed as the firstparameter:

  1. $cookie = [
  2. 'name' => 'The Cookie Name',
  3. 'value' => 'The Value',
  4. 'expire' => '86500',
  5. 'domain' => '.some-domain.com',
  6. 'path' => '/',
  7. 'prefix' => 'myprefix_',
  8. 'secure' => TRUE,
  9. 'httponly' => FALSE
  10. ];
  11.  
  12. $response->setCookie($cookie);

Notes

Only the name and value are required. To delete a cookie set it with theexpiration blank.

The expiration is set in seconds, which will be added to the currenttime. Do not include the time, but rather only the number of secondsfrom now that you wish the cookie to be valid. If the expiration isset to zero the cookie will only last as long as the browser is open.

For site-wide cookies regardless of how your site is requested, add yourURL to the domain starting with a period, like this:.your-domain.com

The path is usually not needed since the method sets a root path.

The prefix is only needed if you need to avoid name collisions withother identically named cookies for your server.

The secure boolean is only needed if you want to make it a secure cookieby setting it to TRUE.

Discrete Parameters

If you prefer, you can set the cookie by passing data using individualparameters:

  1. $response->setCookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httponly);
  • deleteCookie($name = ''[, $domain = ''[, $path = '/'[, $prefix = '']]])

Parameters:

  1. - **$name** (_mixed_) Cookie name or an array of parameters
  2. - **$domain** (_string_) Cookie domain
  3. - **$path** (_string_) Cookie path
  4. - **$prefix** (_string_) Cookie name prefixReturn type:

void

Delete an existing cookie by setting its expiry to blank.

Notes

Only the name is required.

The prefix is only needed if you need to avoid name collisions withother identically named cookies for your server.

Provide a prefix if cookies should only be deleted for that subset.Provide a domain name if cookies should only be deleted for that domain.Provide a path name if cookies should only be deleted for that path.

If any of the optional parameters are empty, then the same-namedcookie will be deleted across all that apply.

Example:

  1. $response->deleteCookie($name);
  • hasCookie($name = ''[, $value = null[, $prefix = '']])

Parameters:

  1. - **$name** (_mixed_) Cookie name or an array of parameters
  2. - **$value** (_string_) cookie value
  3. - **$prefix** (_string_) Cookie name prefixReturn type:

boolean

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

Notes

Only the name is required. If a prefix is specified, it will bepre-pended to the cookie name.

If no value is given, the method just checks for the existenceof the named cookie. If a value is given, then the method checksthat the cookie exists, and that it has the prescribed value.

Example:

  1. if ($response->hasCookie($name)) ...
  • getCookie($name = ''[, $prefix = ''])

Parameters:

  1. - **$name** (_mixed_) Cookie name
  2. - **$prefix** (_string_) Cookie name prefixReturn type:

boolean

Returns the named cookie, if found, or null.

If no name is given, returns the array of cookies.

Each cookie is returned as an associative array.

Example:

  1. $cookie = $response->getCookie($name);