쿠키
HTTP 쿠키 (웹 쿠키, 브라우저 쿠키)는 서버가 사용자의 웹 브라우저로 전송하는 작은 데이터 조각입니다. 브라우저는 이를 저장했다가 이후 동일한 서버에 요청을 보낼 때 함께 전송할 수 있습니다. 일반적으로 두 요청이 동일한 브라우저에서 왔는지 확인하는 데 사용되며, 예를 들어 사용자의 로그인 상태를 유지하는 데 쓰입니다. 상태가 없는 HTTP 프로토콜에서 상태 정보를 기억하는 역할을 합니다.
쿠키는 주로 세 가지 목적으로 사용됩니다:
세션 관리: 로그인, 장바구니, 게임 점수 등 서버가 기억해야 하는 모든 정보
개인화: 사용자 환경 설정, 테마 및 기타 설정
추적: 사용자 행동 기록 및 분석
브라우저에 쿠키를 효율적으로 전송할 수 있도록 CodeIgniter는 쿠키 상호 작용을 추상화한 CodeIgniter\Cookie\Cookie클래스를 제공합니다.
쿠키 생성
현재 새로운 Cookie 값 객체를 생성하는 방법은 네 가지가 있습니다.
<?php
use CodeIgniter\Cookie\Cookie;
use DateTime;
// Using the constructor
$cookie = new Cookie(
'remember_token',
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
[
'expires' => new DateTime('+2 hours'),
'prefix' => '__Secure-',
'path' => '/',
'domain' => '',
'secure' => true,
'httponly' => true,
'raw' => false,
'samesite' => Cookie::SAMESITE_LAX,
],
);
// Supplying a Set-Cookie header string
$cookie = Cookie::fromHeaderString(
'remember_token=f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6; Path=/; Secure; HttpOnly; SameSite=Lax',
false, // raw
);
// Using the fluent builder interface
$cookie = (new Cookie('remember_token'))
->withValue('f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6')
->withPrefix('__Secure-')
->withExpires(new DateTime('+2 hours'))
->withPath('/')
->withDomain('')
->withSecure(true)
->withHTTPOnly(true)
->withSameSite(Cookie::SAMESITE_LAX);
// Using the global function `cookie` which implicitly calls `new Cookie()`
$cookie = cookie('remember_token', 'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6');
Cookie 객체를 생성할 때 name 속성만 필수입니다. 나머지는 모두 선택 사항입니다. 선택적 속성을 수정하지 않으면 Cookie클래스에 저장된 기본값으로 채워집니다.
기본값 재정의
클래스에 현재 저장된 기본값을 재정의하려면 Config\Cookie 인스턴스나 기본값 배열을 정적 메서드 Cookie::setDefaults()에 전달하면 됩니다.
<?php
use CodeIgniter\Cookie\Cookie;
use Config\Cookie as CookieConfig;
// pass in a Config\Cookie instance before constructing a Cookie class
Cookie::setDefaults(config(CookieConfig::class));
$cookie = new Cookie('login_token');
// pass in an array of defaults
$myDefaults = [
'expires' => 0,
'samesite' => Cookie::SAMESITE_STRICT,
];
Cookie::setDefaults($myDefaults);
$cookie = new Cookie('login_token');
Config\Cookie 인스턴스나 배열을 Cookie::setDefaults()에 전달하면 기본값이 덮어써지며, 새로운 기본값이 전달될 때까지 유지됩니다.
일시적으로 기본값 변경
이러한 동작을 원하지 않고 일시적으로만 기본값을 변경하려면 Cookie::setDefaults()의 반환값(이전 기본값 배열)을 활용할 수 있습니다.
<?php
use CodeIgniter\Cookie\Cookie;
use Config\Cookie as CookieConfig;
$oldDefaults = Cookie::setDefaults(config(CookieConfig::class));
$cookie = new Cookie('my_token', 'muffins');
// return the old defaults
Cookie::setDefaults($oldDefaults);
쿠키 속성 접근
인스턴스를 생성한 후에는 getter 메서드를 사용하여 Cookie의 속성에 쉽게 접근할 수 있습니다.
<?php
use CodeIgniter\Cookie\Cookie;
use DateTime;
use DateTimeZone;
$cookie = new Cookie(
'remember_token',
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
[
'expires' => new DateTime('2025-02-14 00:00:00', new DateTimeZone('UTC')),
'prefix' => '__Secure-',
'path' => '/',
'domain' => '',
'secure' => true,
'httponly' => true,
'raw' => false,
'samesite' => Cookie::SAMESITE_LAX,
],
);
$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'
// additional getter
$cookie->getId(); // '__Secure-remember_token;;/'
// when using `setcookie()`'s alternative signature on PHP 7.3+
// you can easily use the `getOptions()` method to supply the
// $options parameter
$cookie->getOptions();
불변 쿠키
새로운 Cookie 인스턴스는 HTTP 쿠키의 불변 값 객체 표현입니다. 불변이기 때문에 인스턴스의 속성을 수정해도 원본 인스턴스에는 영향을 주지 않습니다. 수정은 항상 새로운 인스턴스를 반환합니다. 이를 사용하려면 새로운 인스턴스를 저장해야 합니다.
<?php
use CodeIgniter\Cookie\Cookie;
$cookie = new Cookie('login_token', 'admin');
$cookie->getName(); // 'login_token'
$cookie->withName('remember_token');
$cookie->getName(); // 'login_token'
$new = $cookie->withName('remember_token');
$new->getName(); // 'remember_token'
쿠키 속성 유효성 검사
HTTP 쿠키는 브라우저에서 수락되기 위해 따라야 하는 여러 사양에 의해 규제됩니다. 따라서 Cookie의 특정 속성을 생성하거나 수정할 때 사양을 준수하는지 확인하기 위해 유효성 검사가 수행됩니다.
위반 사항이 발견되면 CookieException이 발생합니다.
이름 속성 유효성 검사
쿠키 이름은 다음을 제외한 모든 US-ASCII 문자를 사용할 수 있습니다:
제어 문자;
공백 또는 탭;
( ) < > @ , ; : \ " / [ ] ? = { }와 같은 구분 문자
$raw 매개변수를 true로 설정하면 이 유효성 검사가 엄격하게 수행됩니다. PHP의 setcookie()와 setrawcookie()는 유효하지 않은 이름의 쿠키를 거부하기 때문입니다. 또한 쿠키 이름은 빈 문자열이 될 수 없습니다.
접두사 속성 유효성 검사
__Secure- 접두사를 사용할 때는 쿠키의 $secure 플래그를 true로 설정해야 합니다. __Host- 접두사를 사용할 경우 쿠키는 다음 조건을 충족해야 합니다:
$secure플래그가true로 설정되어 있어야 함$domain이 비어 있어야 함$path가/이어야 함
SameSite 속성 유효성 검사
SameSite 속성은 세 가지 값을 허용합니다:
Lax: 일반적인 크로스 사이트 서브요청(예: 제3자 사이트에 이미지나 프레임을 로드하는 경우)에는 쿠키가 전송되지 않지만, 사용자가 원본 사이트로 이동할 때(즉 링크를 따라갈 때)는 전송됩니다.
Strict: 쿠키는 퍼스트 파티 컨텍스트에서만 전송되며, 제3자 웹사이트에서 시작된 요청과 함께 전송되지 않습니다.
None: 쿠키는 모든 컨텍스트에서 전송됩니다. 즉 퍼스트 파티 요청과 크로스 오리진 요청 모두에 대한 응답에서 전송됩니다.
그러나 CodeIgniter는 SameSite 속성을 빈 문자열로 설정할 수 있도록 허용합니다. 빈 문자열이 제공되면 Cookie클래스에 저장된 기본 SameSite 설정이 사용됩니다. 위에서 설명한 대로 Cookie::setDefaults()를 사용하여 기본 SameSite를 변경할 수 있습니다.
최근 쿠키 사양이 변경되어 현대 브라우저는 SameSite가 제공되지 않으면 기본값을 부여하도록 요구받고 있습니다. 이 기본값은 Lax입니다. SameSite를 빈 문자열로 설정하고 기본 SameSite도 빈 문자열인 경우, 쿠키에 Lax 값이 부여됩니다.
SameSite를 None으로 설정한 경우 Secure도 true로 설정되어 있는지 확인해야 합니다.
SameSite 속성을 작성할 때 Cookie클래스는 대소문자를 구분하지 않고 값을 허용합니다. 번거롭지 않도록 클래스의 상수를 활용할 수도 있습니다.
<?php
use CodeIgniter\Cookie\Cookie;
Cookie::SAMESITE_LAX; // 'Lax'
Cookie::SAMESITE_STRICT; // 'Strict'
Cookie::SAMESITE_NONE; // 'None'
쿠키 전송
Response 객체의 CookieStore에 Cookie 객체를 설정하면 프레임워크가 자동으로 쿠키를 전송합니다.
CodeIgniter\HTTP\Response::setCookie()를 사용하여 설정합니다:
<?php
use CodeIgniter\Cookie\Cookie;
$response = service('response');
$cookie = new Cookie(
'remember_token',
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
[
'max-age' => 3600 * 2, // Expires in 2 hours
],
);
$response->setCookie($cookie);
set_cookie() 헬퍼 함수를 사용할 수도 있습니다:
<?php
use CodeIgniter\Cookie\Cookie;
helper('cookie');
$cookie = new Cookie(
'remember_token',
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
[
'max-age' => 3600 * 2, // Expires in 2 hours
],
);
set_cookie($cookie);
쿠키 저장소 사용
참고
일반적으로 CookieStore를 직접 사용할 필요는 없습니다.
CookieStore클래스는 Cookie 객체의 불변 컬렉션을 나타냅니다.
Response에서 저장소 가져오기
CookieStore 인스턴스는 현재 Response 객체에서 접근할 수 있습니다.
<?php
$cookieStore = service('response')->getCookieStore();
CookieStore 생성
CodeIgniter는 CookieStore의 새 인스턴스를 생성하는 세 가지 다른 방법을 제공합니다.
<?php
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
// Passing an array of `Cookie` objects in the constructor
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
// Passing an array of `Set-Cookie` header strings
$store = CookieStore::fromCookieHeaders([
'remember_token=me; Path=/; SameSite=Lax',
'login_token=admin; Path=/; SameSite=Lax',
]);
// using the global `cookies` function
$store = cookies([new Cookie('login_token')], false);
// retrieving the `CookieStore` instance saved in our current `Response` object
$store = cookies();
참고
전역 cookies() 함수를 사용할 때, 전달된 Cookie 배열은 두 번째 인수인 $getGlobal이 false로 설정된 경우에만 고려됩니다.
저장소의 쿠키 확인
CookieStore 인스턴스에 Cookie 객체가 존재하는지 확인하려면 여러 방법을 사용할 수 있습니다:
<?php
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
// check if cookie is in the current cookie collection
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
$store->has('login_token');
// check if cookie is in the current Response's cookie collection
cookies()->has('login_token');
service('response')->hasCookie('remember_token');
// using the cookie helper to check the current Response
// not available to v4.1.1 and lower
helper('cookie');
has_cookie('login_token');
저장소의 쿠키 가져오기
쿠키 컬렉션에서 Cookie 인스턴스를 가져오는 것은 매우 간단합니다:
<?php
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
use Config\Services;
// getting cookie in the current cookie collection
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
$store->get('login_token');
// getting cookie in the current Response's cookie collection
cookies()->get('login_token');
service('response')->getCookie('remember_token');
// using the cookie helper to get cookie from the Response's cookie collection
helper('cookie');
get_cookie('remember_token');
CookieStore에서 Cookie 인스턴스를 직접 가져올 때 유효하지 않은 이름은 CookieException을 발생시킵니다.
<?php
// throws CookieException
$store->get('unknown_cookie');
현재 Response의 쿠키 컬렉션에서 Cookie 인스턴스를 가져올 때 유효하지 않은 이름은 단순히 null을 반환합니다.
<?php
cookies()->get('unknown_cookie'); // null
Response에서 쿠키를 가져올 때 인수를 제공하지 않으면 저장소의 모든 Cookie 객체가 반환됩니다.
<?php
cookies()->display(); // array of Cookie objects
// or even from the Response
service('response')->getCookies();
참고
헬퍼 함수 get_cookie()는 Response가 아닌 현재 Request 객체에서 쿠키를 가져옵니다. 이 함수는 $_COOKIE 배열에서 해당 쿠키가 설정되어 있는지 확인하고 즉시 가져옵니다.
저장소에서 쿠키 추가/제거
앞서 언급했듯이 CookieStore 객체는 불변입니다. 수정된 인스턴스를 사용하려면 저장해야 합니다. 원본 인스턴스는 변경되지 않습니다.
<?php
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
// adding a new Cookie instance
$new = $store->put(new Cookie('admin_token', 'yes'));
// removing a Cookie instance
$new = $store->remove('login_token');
참고
저장소에서 쿠키를 제거하는 것은 브라우저에서 쿠키를 삭제하는 것이 아닙니다. 브라우저에서 쿠키를 삭제하려면 동일한 이름으로 빈 값의 쿠키를 저장소에 추가해야 합니다.
현재 Response 객체의 저장소에 있는 쿠키와 상호 작용할 때는 쿠키 컬렉션의 불변 특성을 걱정하지 않고 안전하게 쿠키를 추가하거나 삭제할 수 있습니다. Response 객체가 인스턴스를 수정된 인스턴스로 교체해 줍니다.
<?php
service('response')->setCookie('admin_token', 'yes');
service('response')->deleteCookie('login_token');
// using the cookie helper
helper('cookie');
set_cookie('admin_token', 'yes');
delete_cookie('login_token');
저장소의 쿠키 디스패치
중요
이 메서드는 버전 4.1.6부터 더 이상 사용되지 않으며 4.6.0에서 제거되었습니다.
대부분의 경우 쿠키를 수동으로 전송할 필요가 없습니다. CodeIgniter가 이를 처리해 줍니다. 그러나 정말로 쿠키를 수동으로 전송해야 한다면 dispatch 메서드를 사용할 수 있습니다. 다른 헤더를 전송할 때와 마찬가지로 headers_sent()의 값을 확인하여 헤더가 아직 전송되지 않았는지 확인해야 합니다.
<?php
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
$store->dispatch(); // After dispatch, the collection is now empty.
쿠키 개인화
Cookie클래스 내부에는 쿠키 객체를 원활하게 생성할 수 있도록 적절한 기본값이 설정되어 있습니다. 그러나 app/Config/Cookie.php 파일의 Config\Cookie클래스에서 다음 설정을 변경하여 자신만의 설정을 정의할 수도 있습니다.
설정 |
옵션/타입 |
기본값 |
설명 |
|---|---|---|---|
$prefix |
|
|
쿠키 이름 앞에 붙일 접두사. |
$expires |
|
|
만료 타임스탬프. |
$path |
|
|
쿠키의 경로 속성. |
$domain |
|
|
쿠키의 도메인 속성(후행 슬래시 포함). |
$secure |
|
|
보안 HTTPS를 통해 전송할지 여부. |
$httponly |
|
|
JavaScript로 접근할 수 없는지 여부. |
$samesite |
|
|
SameSite 속성. |
$raw |
|
|
|
런타임에는 Cookie::setDefaults() 메서드를 사용하여 새 기본값을 수동으로 지정할 수 있습니다.
클래스 레퍼런스
- class CodeIgniter\Cookie\Cookie
- static setDefaults([$config = []])
- 매개변수:
$config (
\Config\Cookie|array) – 설정 배열 또는 인스턴스
- 반환 형식:
array- 반환:
이전 기본값
Config\Cookie설정 또는 배열에서 값을 주입하여 Cookie 인스턴스의 기본 속성을 설정합니다.
- static fromHeaderString(string $header[, bool $raw = false])
- 매개변수:
$header (
string) –Set-Cookie헤더 문자열$raw (
bool) – 이 쿠키가 URL 인코딩 없이setrawcookie()를 통해 전송될지 여부
- 반환 형식:
Cookie- 반환:
Cookie인스턴스- 예외:
CookieException
Set-Cookie헤더에서 새로운 Cookie 인스턴스를 생성합니다.
- __construct(string $name[, string $value = ''[, array $options = []]])
- 매개변수:
$name (
string) – 쿠키 이름$value (
string) – 쿠키 값$options (
array) – 쿠키 옵션
- 반환 형식:
Cookie- 반환:
Cookie인스턴스- 예외:
CookieException
새로운 Cookie 인스턴스를 생성합니다.
- getId()
- 반환 형식:
string- 반환:
쿠키 컬렉션에서 인덱싱에 사용되는 ID.
- getPrefix() → string
- getName() → string
- getPrefixedName() → string
- getValue() → string
- getExpiresTimestamp() → int
- getExpiresString() → string
- isExpired() → bool
- getMaxAge() → int
- getDomain() → string
- getPath() → string
- isSecure() → bool
- isHTTPOnly() → bool
- getSameSite() → string
- isRaw() → bool
- getOptions() → array
- withRaw([bool $raw = true])
- 매개변수:
$raw (
bool)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
URL 인코딩 옵션을 업데이트한 새로운 Cookie를 생성합니다.
- withPrefix([string $prefix = ''])
- 매개변수:
$prefix (
string)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 접두사를 가진 Cookie를 생성합니다.
- withName(string $name)
- 매개변수:
$name (
string)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 이름을 가진 Cookie를 생성합니다.
- withValue(string $value)
- 매개변수:
$value (
string)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 값을 가진 Cookie를 생성합니다.
- withExpires($expires)
- 매개변수:
$expires (
DateTimeInterface|string|int)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 만료 시간을 가진 Cookie를 생성합니다.
- withExpired()
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
브라우저에서 만료될 새로운 Cookie를 생성합니다.
- withNeverExpiring()
중요
이 메서드는 버전 4.2.6부터 더 이상 사용되지 않으며 4.6.0에서 제거되었습니다.
- 매개변수:
$name (
string)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
사실상 만료되지 않는 새로운 Cookie를 생성합니다.
- withDomain(?string $domain)
- 매개변수:
$domain (
string|null)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 도메인을 가진 Cookie를 생성합니다.
- withPath(?string $path)
- 매개변수:
$path (
string|null)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 경로를 가진 Cookie를 생성합니다.
- withSecure([bool $secure = true])
- 매개변수:
$secure (
bool)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 “Secure” 속성을 가진 Cookie를 생성합니다.
- withHTTPOnly([bool $httponly = true])
- 매개변수:
$httponly (
bool)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 “HttpOnly” 속성을 가진 Cookie를 생성합니다.
- withSameSite(string $samesite)
- 매개변수:
$samesite (
string)
- 반환 형식:
Cookie- 반환:
새로운
Cookie인스턴스
새로운 “SameSite” 속성을 가진 Cookie를 생성합니다.
- toHeaderString()
- 반환 형식:
string- 반환:
헤더 문자열로 전달할 수 있는 문자열 표현을 반환합니다.
- toArray()
- 반환 형식:
array- 반환:
Cookie 인스턴스의 배열 표현을 반환합니다.
- class CodeIgniter\Cookie\CookieStore
- static fromCookieHeaders(array $headers[, bool $raw = false])
- 매개변수:
$header (
array) –Set-Cookie헤더 배열$raw (
bool) – URL 인코딩을 사용하지 않을지 여부
- 반환 형식:
CookieStore- 반환:
CookieStore인스턴스- 예외:
CookieException
Set-Cookie헤더 배열에서 CookieStore를 생성합니다.
- __construct(array $cookies)
- 매개변수:
$cookies (
array) –Cookie객체 배열
- 반환 형식:
CookieStore- 반환:
CookieStore인스턴스- 예외:
CookieException
- has(string $name[, string $prefix = ''[, ?string $value = null]]) → bool
- 매개변수:
$name (
string) – 쿠키 이름$prefix (
string) – 쿠키 접두사$value (
string|null) – 쿠키 값
- 반환 형식:
bool- 반환:
이름과 접두사로 식별된
Cookie객체가 컬렉션에 존재하는지 확인합니다.
- get(string $name[, string $prefix = '']) → Cookie
- 매개변수:
$name (
string) – 쿠키 이름$prefix (
string) – 쿠키 접두사
- 반환 형식:
Cookie- 반환:
이름과 접두사로 식별된 Cookie 인스턴스를 가져옵니다.
- 예외:
CookieException
- put(Cookie $cookie) → CookieStore
- 매개변수:
$cookie (
Cookie) – Cookie 객체
- 반환 형식:
CookieStore- 반환:
새로운
CookieStore인스턴스
새로운 쿠키를 저장하고 새로운 컬렉션을 반환합니다. 원본 컬렉션은 변경되지 않습니다.
- remove(string $name[, string $prefix = '']) → CookieStore
- 매개변수:
$name (
string) – 쿠키 이름$prefix (
string) – 쿠키 접두사
- 반환 형식:
CookieStore- 반환:
새로운
CookieStore인스턴스
컬렉션에서 쿠키를 제거하고 업데이트된 컬렉션을 반환합니다. 원본 컬렉션은 변경되지 않습니다.
- dispatch() → void
중요
이 메서드는 버전 4.1.6부터 더 이상 사용되지 않으며 4.6.0에서 제거되었습니다.
- 반환 형식:
void
저장소의 모든 쿠키를 디스패치합니다.
- display() → array
- 반환 형식:
array- 반환:
저장소의 모든 쿠키 인스턴스를 반환합니다.
- clear() → void
- 반환 형식:
void
쿠키 컬렉션을 초기화합니다.