Skip to content

Commit 06fe970

Browse files
authored
Merge pull request #7778 from kenjis/fix-docs-cookies
docs: improve cookies
2 parents c640145 + 0dbd58a commit 06fe970

9 files changed

Lines changed: 121 additions & 45 deletions

File tree

system/Cookie/Cookie.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ class Cookie implements ArrayAccess, CloneableCookieInterface
5858
protected $value;
5959

6060
/**
61-
* @var int
61+
* @var int Unix timestamp
6262
*/
6363
protected $expires;
6464

system/Helpers/cookie_helper.php

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@
99
* the LICENSE file that was distributed with this source code.
1010
*/
1111

12+
use CodeIgniter\Cookie\Cookie;
1213
use Config\App;
13-
use Config\Cookie;
14+
use Config\Cookie as CookieConfig;
1415
use Config\Services;
1516

1617
// =============================================================================
@@ -24,15 +25,15 @@
2425
* Accepts seven parameters, or you can submit an associative
2526
* array in the first parameter containing all the values.
2627
*
27-
* @param array|string $name Cookie name or array containing binds
28-
* @param string $value The value of the cookie
29-
* @param string $expire The number of seconds until expiration
30-
* @param string $domain For site-wide cookie. Usually: .yourdomain.com
31-
* @param string $path The cookie path
32-
* @param string $prefix The cookie prefix ('': the default prefix)
33-
* @param bool|null $secure True makes the cookie secure
34-
* @param bool|null $httpOnly True makes the cookie accessible via http(s) only (no javascript)
35-
* @param string|null $sameSite The cookie SameSite value
28+
* @param array|Cookie|string $name Cookie name / array containing binds / Cookie object
29+
* @param string $value The value of the cookie
30+
* @param string $expire The number of seconds until expiration
31+
* @param string $domain For site-wide cookie. Usually: .yourdomain.com
32+
* @param string $path The cookie path
33+
* @param string $prefix The cookie prefix ('': the default prefix)
34+
* @param bool|null $secure True makes the cookie secure
35+
* @param bool|null $httpOnly True makes the cookie accessible via http(s) only (no javascript)
36+
* @param string|null $sameSite The cookie SameSite value
3637
*
3738
* @return void
3839
*
@@ -70,11 +71,11 @@ function set_cookie(
7071
function get_cookie($index, bool $xssClean = false, ?string $prefix = '')
7172
{
7273
if ($prefix === '') {
73-
/** @var Cookie|null $cookie */
74-
$cookie = config(Cookie::class);
74+
/** @var CookieConfig|null $cookie */
75+
$cookie = config(CookieConfig::class);
7576

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

8081
$request = Services::request();

user_guide_src/source/helpers/cookie_helper.rst

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ The following functions are available:
2323

2424
.. php:function:: set_cookie($name[, $value = ''[, $expire = ''[, $domain = ''[, $path = '/'[, $prefix = ''[, $secure = false[, $httpOnly = false[, $sameSite = '']]]]]]]])
2525
26-
:param mixed $name: Cookie name *or* associative array of all of the parameters available to this function
26+
: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``
2727
:param string $value: Cookie value
2828
:param int $expire: Number of seconds until expiration. If set to ``0`` the cookie will only last as long as the browser is open
2929
:param string $domain: Cookie domain (usually: .yourdomain.com)
@@ -55,11 +55,12 @@ The following functions are available:
5555
This helper function gives you friendlier syntax to get browser
5656
cookies. Refer to the :doc:`IncomingRequest Library </incoming/incomingrequest>` for
5757
detailed description of its use, as this function acts very
58-
similarly to ``IncomingRequest::getCookie()``, except it will also prepend
58+
similarly to :php:meth:`CodeIgniter\\HTTP\\IncomingRequest::getCookie()`,
59+
except it will also prepend
5960
the ``Config\Cookie::$prefix`` that you might've set in your
6061
**app/Config/Cookie.php** file.
6162

62-
.. 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.
63+
.. 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.
6364

6465
.. php:function:: delete_cookie($name[, $domain = ''[, $path = '/'[, $prefix = '']]])
6566
@@ -74,10 +75,10 @@ The following functions are available:
7475

7576
.. literalinclude:: cookie_helper/002.php
7677

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

80-
.. note:: When you use ``set_cookie()``,
81+
.. note:: When you use :php:func:`set_cookie()`,
8182
if the ``value`` is set to empty string and the ``expire`` is set to ``0``, the cookie will be deleted.
8283
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.
8384

user_guide_src/source/libraries/cookies.rst

Lines changed: 53 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ Cookies are mainly used for three purposes:
1414
- **Personalization**: User preferences, themes, and other settings
1515
- **Tracking**: Recording and analyzing user behavior
1616

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

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

3333
When constructing the ``Cookie`` object, only the ``name`` attribute is required. All other else are optional.
3434
If the optional attributes are not modified, their values will be filled up by the default values saved in
35-
the ``Cookie`` class. To override the defaults currently stored in the class, you can pass a ``Config\Cookie``
35+
the ``Cookie`` class.
36+
37+
Overriding Defaults
38+
===================
39+
40+
To override the defaults currently stored in the class, you can pass a ``Config\Cookie``
3641
instance or an array of defaults to the static ``Cookie::setDefaults()`` method.
3742

3843
.. literalinclude:: cookies/002.php
3944

4045
Passing the ``Config\Cookie`` instance or an array to ``Cookie::setDefaults()`` will effectively
41-
overwrite your defaults and will persist until new defaults are passed. If you do not want this
46+
overwrite your defaults and will persist until new defaults are passed.
47+
48+
Changing Defaults for a Limited Time
49+
------------------------------------
50+
51+
If you do not want this
4252
behavior but only want to change defaults for a limited time, you can take advantage of
4353
``Cookie::setDefaults()`` return which returns the old defaults array.
4454

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

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

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

120132
.. literalinclude:: cookies/006.php
121133

134+
135+
***************
136+
Sending Cookies
137+
***************
138+
139+
Set the ``Cookie`` objects in the ``CookieStore`` of the Response object, and
140+
the framework will automatically send the cookies.
141+
142+
Use :php:meth:`CodeIgniter\\HTTP\\Response::setCookie()` to set:
143+
144+
.. literalinclude:: cookies/017.php
145+
146+
You can also use the :php:func:`set_cookie()` helper function:
147+
148+
.. literalinclude:: cookies/018.php
149+
150+
122151
**********************
123152
Using the Cookie Store
124153
**********************
125154

126-
The ``CookieStore`` class represents an immutable collection of ``Cookie`` objects. The ``CookieStore``
155+
.. note:: Normally, there is no need to use CookieStore directly.
156+
157+
The ``CookieStore`` class represents an immutable collection of ``Cookie`` objects.
158+
159+
Getting the Store from Response
160+
===============================
161+
162+
The ``CookieStore``
127163
instance can be accessed from the current ``Response`` object.
128164

129165
.. literalinclude:: cookies/007.php
130166

167+
Creating CookieStore
168+
====================
169+
131170
CodeIgniter provides three (3) other ways to create a new instance of the ``CookieStore``.
132171

133172
.. literalinclude:: cookies/008.php
134173

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

138177
Checking Cookies in Store
@@ -164,8 +203,8 @@ in store will be displayed.
164203

165204
.. literalinclude:: cookies/013.php
166205

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

171210
Adding/Removing Cookies in Store
@@ -189,6 +228,10 @@ the instance with the modified instance.
189228
Dispatching Cookies in Store
190229
============================
191230

231+
.. deprecated:: 4.1.6
232+
233+
.. important:: This method is deprecated. It will be removed in future releases.
234+
192235
More often than not, you do not need to concern yourself in manually sending cookies. CodeIgniter will do this
193236
for you. However, if you really need to manually send cookies, you can use the ``dispatch`` method. Just like
194237
in sending other headers, you need to make sure the headers are not yet sent by checking the value
@@ -229,11 +272,11 @@ Class Reference
229272
230273
.. php:staticmethod:: setDefaults([$config = []])
231274
232-
:param \Config\Cookie|array $config: The configuration array or instance
275+
:param \\Config\\Cookie|array $config: The configuration array or instance
233276
:rtype: array<string, mixed>
234277
:returns: The old defaults
235278

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

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

user_guide_src/source/libraries/cookies/004.php

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,19 @@
1919
]
2020
);
2121

22-
$cookie->getName(); // 'remember_token'
23-
$cookie->getPrefix(); // '__Secure-'
24-
$cookie->getPrefixedName(); // '__Secure-remember_token'
22+
$cookie->getName(); // 'remember_token'
23+
$cookie->getPrefix(); // '__Secure-'
24+
$cookie->getPrefixedName(); // '__Secure-remember_token'
2525
$cookie->getExpiresTimestamp(); // Unix timestamp
26-
$cookie->getExpiresString(); // 'Fri, 14-Feb-2025 00:00:00 GMT'
27-
$cookie->isExpired(); // false
28-
$cookie->getMaxAge(); // the difference from time() to expires
29-
$cookie->isRaw(); // false
30-
$cookie->isSecure(); // true
31-
$cookie->getPath(); // '/'
32-
$cookie->getDomain(); // ''
33-
$cookie->isHTTPOnly(); // true
34-
$cookie->getSameSite(); // 'Lax'
26+
$cookie->getExpiresString(); // 'Fri, 14-Feb-2025 00:00:00 GMT'
27+
$cookie->isExpired(); // false
28+
$cookie->getMaxAge(); // the difference from time() to expires
29+
$cookie->isRaw(); // false
30+
$cookie->isSecure(); // true
31+
$cookie->getPath(); // '/'
32+
$cookie->getDomain(); // ''
33+
$cookie->isHTTPOnly(); // true
34+
$cookie->getSameSite(); // 'Lax'
3535

3636
// additional getter
3737
$cookie->getId(); // '__Secure-remember_token;;/'

user_guide_src/source/libraries/cookies/006.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33
use CodeIgniter\Cookie\Cookie;
44

5-
Cookie::SAMESITE_LAX; // 'lax'
6-
Cookie::SAMESITE_STRICT; // 'strict'
7-
Cookie::SAMESITE_NONE; // 'none'
5+
Cookie::SAMESITE_LAX; // 'lax'
6+
Cookie::SAMESITE_STRICT; // 'strict'
7+
Cookie::SAMESITE_NONE; // 'none'
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
use CodeIgniter\Cookie\Cookie;
4+
use Config\Services;
5+
6+
$response = Services::response();
7+
8+
$cookie = new Cookie(
9+
'remember_token',
10+
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
11+
[
12+
'max-age' => 3600 * 2, // Expires in 2 hours
13+
]
14+
);
15+
16+
$response->setCookie($cookie);
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
use CodeIgniter\Cookie\Cookie;
4+
5+
helper('cookie');
6+
7+
$cookie = new Cookie(
8+
'remember_token',
9+
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
10+
[
11+
'max-age' => 3600 * 2, // Expires in 2 hours
12+
]
13+
);
14+
15+
set_cookie($cookie);

user_guide_src/source/outgoing/response.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -445,7 +445,7 @@ The methods provided by the parent class that are available are:
445445

446446
.. php:method:: setCookie($name = ''[, $value = ''[, $expire = ''[, $domain = ''[, $path = '/'[, $prefix = ''[, $secure = false[, $httponly = false[, $samesite = null]]]]]]]])
447447
448-
:param array|Cookie|string $name: Cookie name or an array of parameters or an instance of ``CodeIgniter\Cookie\Cookie``
448+
: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``
449449
:param string $value: Cookie value
450450
:param int $expire: Cookie expiration time in seconds. If set to ``0`` the cookie will only last as long as the browser is open
451451
:param string $domain: Cookie domain

0 commit comments

Comments
 (0)