PHP setcookie() 함수
예시
다음 예에서는 값이 "John Doe"인 "user"라는 쿠키를 만듭니다. 쿠키는 30일(86400 * 30) 후에 만료됩니다. "/"는 쿠키가 전체 웹사이트에서 사용 가능함을 의미합니다(그렇지 않으면 선호하는 디렉토리 선택).
그런 다음 쿠키 "user"의 값을 검색합니다(전역 변수 $_COOKIE 사용). 또한 isset() 함수를 사용하여 쿠키가 설정되었는지 확인합니다.
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
정의 및 사용
setcookie() 함수는 나머지 HTTP 헤더와 함께 보낼 쿠키를 정의합니다.
쿠키는 종종 사용자를 식별하는 데 사용됩니다. 쿠키는 서버가 사용자의 컴퓨터에 삽입하는 작은 파일입니다. 같은 컴퓨터가 브라우저로 페이지를 요청할 때마다 쿠키도 보냅니다. PHP를 사용하면 쿠키 값을 만들고 검색할 수 있습니다.
쿠키 이름은 같은 이름의 변수에 자동으로 할당됩니다. 예를 들어 쿠키가 "user"라는 이름으로 전송된 경우 쿠키 값이 포함된 $user라는 변수가 자동으로 생성됩니다.
참고: setcookie() 함수는 <html> 태그 앞에 나타나야 합니다.
참고: 쿠키 값은 쿠키를 보낼 때 자동으로 URL인코딩되고, 받을 때 자동으로 디코딩됩니다(URL인코딩을 방지하려면 대신 setrawcookie() 사용).
통사론
setcookie(name, value, expire, path, domain, secure, httponly);
매개변수 값
Parameter | Description |
---|---|
name | Required. Specifies the name of the cookie |
value | Optional. Specifies the value of the cookie |
expire | Optional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0 |
path | Optional. Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in |
domain | Optional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain |
secure | Optional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE |
httponly | Optional. If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE |
기술적 세부 사항
반환 값: | 성공 시 TRUE입니다. 실패시 FALSE |
---|---|
PHP 버전: | 4+ |
PHP 변경 로그: | PHP 5.5 - 클라이언트로 전송된 Set-Cookie 헤더에 Max-Age 속성이 포함되었습니다. PHP 5.2 - httponly 매개변수가 추가되었습니다. |
더 많은 예
예시
쿠키의 여러 만료 날짜:
<?php
$value = "Hello world!";
// cookie will expire when the browser close
setcookie("myCookie", $value);
// cookie will expire in 1 hour
setcookie("myCookie", $value, time() + 3600);
// cookie will expire in 1 hour, and will only be available
// within the php directory + all sub-directories of php
setcookie("myCookie", $value, time() + 3600, "/php/");
?>
<html>
<body>
...some code...
</body>
</html>
예시
쿠키를 수정하려면 setcookie() 함수를 사용하여 쿠키를 (다시) 설정하십시오.
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
예시
쿠키를 삭제하려면 만료 날짜가 과거인 setcookie() 함수를 사용하십시오.
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
예시
쿠키가 활성화되었는지 확인하는 작은 스크립트를 만듭니다. 먼저 setcookie() 함수를 사용하여 테스트 쿠키를 만든 다음 $_COOKIE 배열 변수를 계산합니다.
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
❮ PHP 네트워크 참조