Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion system/Cookie/Cookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class Cookie implements ArrayAccess, CloneableCookieInterface
protected $value;

/**
* @var int
* @var int Unix timestamp
*/
protected $expires;

Expand Down
27 changes: 14 additions & 13 deletions system/Helpers/cookie_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
* the LICENSE file that was distributed with this source code.
*/

use CodeIgniter\Cookie\Cookie;
use Config\App;
use Config\Cookie;
use Config\Cookie as CookieConfig;
use Config\Services;

// =============================================================================
Expand All @@ -24,15 +25,15 @@
* Accepts seven parameters, or you can submit an associative
* array in the first parameter containing all the values.
*
* @param array|string $name Cookie name or array containing binds
* @param string $value The value of the cookie
* @param string $expire The number of seconds until expiration
* @param string $domain For site-wide cookie. Usually: .yourdomain.com
* @param string $path The cookie path
* @param string $prefix The cookie prefix ('': the default prefix)
* @param bool|null $secure True makes the cookie secure
* @param bool|null $httpOnly True makes the cookie accessible via http(s) only (no javascript)
* @param string|null $sameSite The cookie SameSite value
* @param array|Cookie|string $name Cookie name / array containing binds / Cookie object
* @param string $value The value of the cookie
* @param string $expire The number of seconds until expiration
* @param string $domain For site-wide cookie. Usually: .yourdomain.com
* @param string $path The cookie path
* @param string $prefix The cookie prefix ('': the default prefix)
* @param bool|null $secure True makes the cookie secure
* @param bool|null $httpOnly True makes the cookie accessible via http(s) only (no javascript)
* @param string|null $sameSite The cookie SameSite value
*
* @see \CodeIgniter\HTTP\Response::setCookie()
*/
Expand Down Expand Up @@ -68,11 +69,11 @@ function set_cookie(
function get_cookie($index, bool $xssClean = false, ?string $prefix = '')
{
if ($prefix === '') {
/** @var Cookie|null $cookie */
$cookie = config(Cookie::class);
/** @var CookieConfig|null $cookie */
$cookie = config(CookieConfig::class);

// @TODO Remove Config\App fallback when deprecated `App` members are removed.
$prefix = $cookie instanceof Cookie ? $cookie->prefix : config(App::class)->cookiePrefix;
$prefix = $cookie instanceof CookieConfig ? $cookie->prefix : config(App::class)->cookiePrefix;
}

$request = Services::request();
Expand Down
11 changes: 6 additions & 5 deletions user_guide_src/source/helpers/cookie_helper.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ The following functions are available:

.. php:function:: set_cookie($name[, $value = ''[, $expire = ''[, $domain = ''[, $path = '/'[, $prefix = ''[, $secure = false[, $httpOnly = false[, $sameSite = '']]]]]]]])

:param mixed $name: Cookie name *or* associative array of all of the parameters available to this function
:param array|Cookie|string $name: Cookie name *or* associative array of all of the parameters available to this function *or* an instance of ``CodeIgniter\Cookie\Cookie``
:param string $value: Cookie value
:param int $expire: Number of seconds until expiration. If set to ``0`` the cookie will only last as long as the browser is open
:param string $domain: Cookie domain (usually: .yourdomain.com)
Expand Down Expand Up @@ -55,11 +55,12 @@ The following functions are available:
This helper function gives you friendlier syntax to get browser
cookies. Refer to the :doc:`IncomingRequest Library </incoming/incomingrequest>` for
detailed description of its use, as this function acts very
similarly to ``IncomingRequest::getCookie()``, except it will also prepend
similarly to :php:meth:`CodeIgniter\\HTTP\\IncomingRequest::getCookie()`,
except it will also prepend
the ``Config\Cookie::$prefix`` that you might've set in your
**app/Config/Cookie.php** file.

.. warning:: Using XSS filtering is a bad practice. It does not prevent XSS attacks perfectly. Using ``esc()`` with the correct ``$context`` in the views is recommended.
.. warning:: Using XSS filtering is a bad practice. It does not prevent XSS attacks perfectly. Using :php:func:`esc()` with the correct ``$context`` in the views is recommended.

.. php:function:: delete_cookie($name[, $domain = ''[, $path = '/'[, $prefix = '']]])

Expand All @@ -74,10 +75,10 @@ The following functions are available:

.. literalinclude:: cookie_helper/002.php

This function is otherwise identical to ``set_cookie()``, except that it
This function is otherwise identical to :php:func:`set_cookie()`, except that it
does not have the ``value`` and ``expire`` parameters.

.. note:: When you use ``set_cookie()``,
.. note:: When you use :php:func:`set_cookie()`,
if the ``value`` is set to empty string and the ``expire`` is set to ``0``, the cookie will be deleted.
If the ``value`` is set to non-empty string and the ``expire`` is set to ``0``, the cookie will only last as long as the browser is open.

Expand Down
63 changes: 53 additions & 10 deletions user_guide_src/source/libraries/cookies.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Cookies are mainly used for three purposes:
- **Personalization**: User preferences, themes, and other settings
- **Tracking**: Recording and analyzing user behavior

To help you efficiently use cookies across browsers with your request and response,
To help you efficiently send cookies to browsers,
CodeIgniter provides the ``CodeIgniter\Cookie\Cookie`` class to abstract the
cookie interaction.

Expand All @@ -32,13 +32,23 @@ There are currently four (4) ways to create a new ``Cookie`` value object.

When constructing the ``Cookie`` object, only the ``name`` attribute is required. All other else are optional.
If the optional attributes are not modified, their values will be filled up by the default values saved in
the ``Cookie`` class. To override the defaults currently stored in the class, you can pass a ``Config\Cookie``
the ``Cookie`` class.

Overriding Defaults
===================

To override the defaults currently stored in the class, you can pass a ``Config\Cookie``
instance or an array of defaults to the static ``Cookie::setDefaults()`` method.

.. literalinclude:: cookies/002.php

Passing the ``Config\Cookie`` instance or an array to ``Cookie::setDefaults()`` will effectively
overwrite your defaults and will persist until new defaults are passed. If you do not want this
overwrite your defaults and will persist until new defaults are passed.

Changing Defaults for a Limited Time
------------------------------------

If you do not want this
behavior but only want to change defaults for a limited time, you can take advantage of
``Cookie::setDefaults()`` return which returns the old defaults array.

Expand Down Expand Up @@ -82,7 +92,9 @@ A cookie name can be any US-ASCII character, except for the following:
- separator characters, such as ``( ) < > @ , ; : \ " / [ ] ? = { }``

If setting the ``$raw`` parameter to ``true`` this validation will be strictly made. This is because
PHP's ``setcookie`` and ``setrawcookie`` will reject cookies with invalid names. Additionally, cookie
PHP's `setcookie() <https://www.php.net/manual/en/function.setcookie.php>`_
and `setrawcookie() <https://www.php.net/manual/en/function.setrawcookie.php>`_
will reject cookies with invalid names. Additionally, cookie
names cannot be an empty string.

Validating the Prefix Attribute
Expand Down Expand Up @@ -119,20 +131,47 @@ also take advantage of the class's constants to make it not a hassle.

.. literalinclude:: cookies/006.php


***************
Sending Cookies
***************

Set the ``Cookie`` objects in the ``CookieStore`` of the Response object, and
the framework will automatically send the cookies.

Use :php:meth:`CodeIgniter\\HTTP\\Response::setCookie()` to set:

.. literalinclude:: cookies/017.php

You can also use the :php:func:`set_cookie()` helper function:

.. literalinclude:: cookies/018.php


**********************
Using the Cookie Store
**********************

The ``CookieStore`` class represents an immutable collection of ``Cookie`` objects. The ``CookieStore``
.. note:: Normally, there is no need to use CookieStore directly.

The ``CookieStore`` class represents an immutable collection of ``Cookie`` objects.

Getting the Store from Response
===============================

The ``CookieStore``
instance can be accessed from the current ``Response`` object.

.. literalinclude:: cookies/007.php

Creating CookieStore
====================

CodeIgniter provides three (3) other ways to create a new instance of the ``CookieStore``.

.. literalinclude:: cookies/008.php

.. note:: When using the global ``cookies()`` function, the passed ``Cookie`` array will only be considered
.. note:: When using the global :php:func:`cookies()` function, the passed ``Cookie`` array will only be considered
if the second argument, ``$getGlobal``, is set to ``false``.

Checking Cookies in Store
Expand Down Expand Up @@ -164,8 +203,8 @@ in store will be displayed.

.. literalinclude:: cookies/013.php

.. note:: The helper function ``get_cookie()`` gets the cookie from the current ``Request`` object, not
from ``Response``. This function checks the `$_COOKIE` array if that cookie is set and fetches it
.. note:: The helper function :php:func:`get_cookie()` gets the cookie from the current ``Request`` object, not
from ``Response``. This function checks the ``$_COOKIE`` array if that cookie is set and fetches it
right away.

Adding/Removing Cookies in Store
Expand All @@ -189,6 +228,10 @@ the instance with the modified instance.
Dispatching Cookies in Store
============================

.. deprecated:: 4.1.6

.. important:: This method is deprecated. It will be removed in future releases.

More often than not, you do not need to concern yourself in manually sending cookies. CodeIgniter will do this
for you. However, if you really need to manually send cookies, you can use the ``dispatch`` method. Just like
in sending other headers, you need to make sure the headers are not yet sent by checking the value
Expand Down Expand Up @@ -229,11 +272,11 @@ Class Reference

.. php:staticmethod:: setDefaults([$config = []])

:param \Config\Cookie|array $config: The configuration array or instance
:param \\Config\\Cookie|array $config: The configuration array or instance
:rtype: array<string, mixed>
:returns: The old defaults

Set the default attributes to a Cookie instance by injecting the values from the ``\Config\Cookie`` config or an array.
Set the default attributes to a Cookie instance by injecting the values from the ``Config\Cookie`` config or an array.

.. php:staticmethod:: fromHeaderString(string $header[, bool $raw = false])

Expand Down
24 changes: 12 additions & 12 deletions user_guide_src/source/libraries/cookies/004.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,19 @@
]
);

$cookie->getName(); // 'remember_token'
$cookie->getPrefix(); // '__Secure-'
$cookie->getPrefixedName(); // '__Secure-remember_token'
$cookie->getName(); // 'remember_token'
$cookie->getPrefix(); // '__Secure-'
$cookie->getPrefixedName(); // '__Secure-remember_token'
$cookie->getExpiresTimestamp(); // Unix timestamp
$cookie->getExpiresString(); // 'Fri, 14-Feb-2025 00:00:00 GMT'
$cookie->isExpired(); // false
$cookie->getMaxAge(); // the difference from time() to expires
$cookie->isRaw(); // false
$cookie->isSecure(); // true
$cookie->getPath(); // '/'
$cookie->getDomain(); // ''
$cookie->isHTTPOnly(); // true
$cookie->getSameSite(); // 'Lax'
$cookie->getExpiresString(); // 'Fri, 14-Feb-2025 00:00:00 GMT'
$cookie->isExpired(); // false
$cookie->getMaxAge(); // the difference from time() to expires
$cookie->isRaw(); // false
$cookie->isSecure(); // true
$cookie->getPath(); // '/'
$cookie->getDomain(); // ''
$cookie->isHTTPOnly(); // true
$cookie->getSameSite(); // 'Lax'

// additional getter
$cookie->getId(); // '__Secure-remember_token;;/'
Expand Down
6 changes: 3 additions & 3 deletions user_guide_src/source/libraries/cookies/006.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

use CodeIgniter\Cookie\Cookie;

Cookie::SAMESITE_LAX; // 'lax'
Cookie::SAMESITE_STRICT; // 'strict'
Cookie::SAMESITE_NONE; // 'none'
Cookie::SAMESITE_LAX; // 'lax'
Cookie::SAMESITE_STRICT; // 'strict'
Cookie::SAMESITE_NONE; // 'none'
16 changes: 16 additions & 0 deletions user_guide_src/source/libraries/cookies/017.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

use CodeIgniter\Cookie\Cookie;
use Config\Services;

$response = Services::response();

$cookie = new Cookie(
'remember_token',
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
[
'max-age' => 3600 * 2, // Expires in 2 hours
]
);

$response->setCookie($cookie);
15 changes: 15 additions & 0 deletions user_guide_src/source/libraries/cookies/018.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

use CodeIgniter\Cookie\Cookie;

helper('cookie');

$cookie = new Cookie(
'remember_token',
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
[
'max-age' => 3600 * 2, // Expires in 2 hours
]
);

set_cookie($cookie);
2 changes: 1 addition & 1 deletion user_guide_src/source/outgoing/response.rst
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ The methods provided by the parent class that are available are:

.. php:method:: setCookie($name = ''[, $value = ''[, $expire = ''[, $domain = ''[, $path = '/'[, $prefix = ''[, $secure = false[, $httponly = false[, $samesite = null]]]]]]]])

:param array|Cookie|string $name: Cookie name or an array of parameters or an instance of ``CodeIgniter\Cookie\Cookie``
:param array|Cookie|string $name: Cookie name *or* associative array of all of the parameters available to this method *or* an instance of ``CodeIgniter\Cookie\Cookie``
:param string $value: Cookie value
:param int $expire: Cookie expiration time in seconds. If set to ``0`` the cookie will only last as long as the browser is open
:param string $domain: Cookie domain
Expand Down