PHP 튜토리얼

PHP 홈 PHP 소개 PHP 설치 PHP 구문 PHP 주석 PHP 변수 PHP 에코 / 인쇄 PHP 데이터 유형 PHP 문자열 PHP 숫자 PHP 수학 PHP 상수 PHP 연산자 PHP If...Else...Elseif PHP 스위치 PHP 루프 PHP 함수 PHP 배열 PHP 슈퍼글로벌 PHP 정규식

PHP 양식

PHP 양식 처리 PHP 양식 유효성 검사 PHP 양식 필요 PHP 양식 URL/이메일 PHP 양식 완성

PHP 고급

PHP 날짜 및 시간 PHP 포함 PHP 파일 처리 PHP 파일 열기/읽기 PHP 파일 생성/쓰기 PHP 파일 업로드 PHP 쿠키 PHP 세션 PHP 필터 PHP 필터 고급 PHP 콜백 함수 PHP JSON PHP 예외

PHP OOP

PHP OOP란? PHP 클래스/객체 PHP 생성자 PHP 소멸자 PHP 액세스 수정자 PHP 상속 PHP 상수 PHP 추상 클래스 PHP 인터페이스 PHP 특성 PHP 정적 메서드 PHP 정적 속성 PHP 네임스페이스 PHP 반복 가능

MySQL 데이터베이스

MySQL 데이터베이스 MySQL 연결 MySQL 생성 DB MySQL 테이블 생성 MySQL 삽입 데이터 MySQL 마지막 ID 가져오기 MySQL은 다중 삽입 MySQL 준비 MySQL 선택 데이터 MySQL 어디 MySQL 주문 기준 MySQL 데이터 삭제 MySQL 업데이트 데이터 MySQL 제한 데이터

PHP XML

PHP XML 파서 PHP SimpleXML 파서 PHP SimpleXML - 가져오기 PHP XML 국외 거주자 PHP XML DOM

PHP - AJAX

AJAX 소개 AJAX PHP AJAX 데이터베이스 AJAX XML AJAX 라이브 검색 AJAX 투표

PHP 예제

PHP 예제 PHP 컴파일러 PHP 퀴즈 PHP 연습 PHP 인증서

PHP 참조

PHP 개요 PHP 배열 PHP 캘린더 PHP 날짜 PHP 디렉토리 PHP 오류 PHP 예외 PHP 파일 시스템 PHP 필터 PHP FTP PHP JSON PHP 키워드 PHP 라이브러리 XML PHP 메일 PHP 수학 PHP 기타 PHP MySQLi PHP 네트워크 PHP 출력 제어 PHP 정규식 PHP SimpleXML PHP 스트림 PHP 문자열 PHP 변수 처리 PHP XML 파서 PHP 우편번호 PHP 시간대

PHP setcookie() 함수

❮ PHP 네트워크 참조

예시

다음 예에서는 값이 "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 네트워크 참조