phpclass/객체정보2001. 3. 2. 14:32
함수의 참조 반환
함수에서 참조 반환(returning references)할 수 있습니다. 참조 반환하기 위해서는 함수 정의에서 함수명 앞에 참조연산자(reference operator) &를 붙입니다.
[code php;gutter:false] function &bar() {
$a = 5;
return $a;
}
foo(bar()); [/code]
함수에서 참조가 아닌 값으로 반환하게 되면 호출측에서 받게 되는 것은 함수 내의 반환값의 복사본을 받게 될 것입니다.
[code php;gutter:false] <?php

class test {
var $mb;

function test($mb="default") {
$this->mb = $mb;
}
}

function foo(&$obj) {
$obj->mb = "in foo()";
return $obj;
}

$a = &new test;
$b = &foo($a);
$b->mb = "object b";
echo $a->mb."\n";
echo $b->mb."\n";

?> [/code]
위와 같이 참조가 아닌 값으로 반환하게 되면 객체 $a와 객체 $b는 완전히 별개의 객체입니다. 따라서 실행결과를 보면 아래와 같이 객체의 멤버변수 $mb의 값은 틀립니다.
in foo()
object b
그러나 참조를 반환하기 위해 함수정의를 function &foo(&$obj)와 같이 수정한다면 객체 $b는 객체 $a의 참조(별명)이 되어 $a와 $b 모두 동일한 객체 내용을 나타내게 됩니다. 즉, $a를 가지고 멤버를 다루더라도 $b의 멤버가 수정되게 되지요. 아래는 수정하였을 때의 실행 결과입니다.
object b
object b
위에서 한가지 더 주의할 것이 있습니다. $b = &foo($a) 에서 대입연산자로 $b를 할당할 때 반드시 참조로 할당하여야 한다는 것입니다. 아무리 함수가 참조를 반환하더라도 $b = foo($a) 와 같이 하게 되면 $b는 $a의 객체가 참조되는 것이 아니라 대입되는 과정에 복사되는 것입니다. 따라서 함수로부터 참조를 반환할 때는 함수 정의 부분과 호출측의 대입 부분 모두 참조연산자 &를 붙여야 합니다.
[code php;gutter:false] function &returns_reference() {
return $someref;
}

$newref =&returns_reference(); [/code]

'phpclass > 객체정보' 카테고리의 다른 글

What Is an Interface?  (0) 2005.10.25
{참조}5.참조 삭제  (0) 2001.03.02
{참조}3.참조에 의한 전달  (0) 2001.03.02
{참조}2.객체생성에서의 참조  (0) 2001.03.02
{참조}1.참조변수의 생성  (0) 2001.03.02
Posted by 방글24
phpclass/객체정보2001. 3. 2. 14:23
매개변수 전달 방식
값에 의한 전달(call by value)
함수의 매개변수는 기본적으로 값에 의한 전달을 합니다. 이 방식으로 값을 전달하게 되면 함수 내에서 값을 변경하게되면 함수 밖에 있는 값을 변경하는 것을 불가능합니다. 값에 의한 전달은 대입연산자에 의한 할당에서와 마찬가지로 원본의 복사본을 함수 내로 전달하기 때문에 복사본을 아무리 변경해 보았자 원본의 내용은 그대로 남아있기 때문입니다.
참조에 의한 전달(passing by reference 또는 call by reference)
참조에 의한 전달을 하게 되면 원본의 별명을 함수 내로 전달하게 되며 이 별명은 원본의 내용을 그대로 나타내고 있습니다. 따라서 함수 내에서 별명에 의해 수정한 내용이 원본에 그대로 반영되는 것입니다. 따라서 매개변수(원본의 내용)를 수정하려면 참조에 의한 전달 방식을 사용하여야 합니다.
참조에 의한 전달
전달 방법
참조에 의해 함수의 매개변수를 전달하면 이러한 매개변수는 호출측의 사용범위를 갖는 동시에 함수 내에서 사용하는 지역변수로도 사용됩니다. 쉬운 말로 하면 호출측에서 사용하는 원본을 함수 내로 직접 보내는 것입니다. 예를 들어 아래와 같은 예제를 실행하면 $a가 6임을 알 수 있습니다.
[code php;gutter:false] function foo (&$var) { // $var은 전역변수 $a의 별명(참조)
$var++;
}

$a=5;
foo ($a);
echo "\$a=$a\n"; [/code]
이것은 함수 foo 내에 있는 변수 $var이 $a와 동일한 내용을 참조하기 때문입니다. 위에서 보면 함수를 호출할 때는 참조표시(reference sign) &(ampersand)가 없으며 단지 함수를 정의하는 부분에만 참조표시를 하고 있습니다. 이와 같이 함수 정의에서만 참조표시를 하더라도 참조에 의한 전달을 정확히 할 수 있습니다. 때에 따라서는 함수 정의에서 참조표시를 하지 않더라도 함수를 호출할 때 참조표시 &를 첨부하여 호출하면 참조에 의한 매개변수 전달을 할 수 있습니다.
기본적으로는 값에 의한 전달을 하고 특별한 경우에만 참조에 의한 전달을 할 필요가 있는 경우에만 이와 같이 호출측에서 참조표시 &를 붙일 수 있습니다. 그러나 이와 같은 방법은 특별한 이유가 없는 한 좋은 방법은 아닙니다. 함수를 정의할 때 매개변수를 참조로 받을 것인지 아니면 평상시와 같이 복사하여 받을 것인지를 결정하는 것이 바람직합니다.
[code php;gutter:false] function foo ($bar) {
$bar .= ' and something extra.';
}

$str = 'This is a string, ';
foo ($str);
echo $str; // outputs 'This is a string, '
foo (&$str);
echo $str; // outputs 'This is a string, and something extra.' [/code]
전달할 수 있는 요소
참조로 전달할 수 있는 요소로는 아래와 같이 "변수", "new문", "함수에서 반환되는 참조"가 있습니다.
▶변수 : foo($a)
▶new문 : foo(new foobar())
▶함수에서 반환되는 참조 :
[code php;gutter:false] function &bar() {
$a = 5;
return $a;
}

foo(bar()); [/code]
전달할 수 없는 요소
위에서 정의된 요소가 아닌, 예를 들어 함수의 반환값이 참조가 아닌 경우, 표현식(expression), 상수를 참조에 의한 매개변수로 전달할 수 없습니다.
[code php;gutter:false] function bar() { // &가 누락되어 함수의 반환값이 참조가 아님
$a = 5;
return $a;
}

foo(bar()); // 함수의 반환값이 참조가 아닌 경우
foo($a = 5) // 표현식
foo(5) // 상수 [/code]
참조는 포인터가 아님.
아래와 같은 예에서 여러분은 실행결과 $bar값이 "91"라고 생각할 지 모르겠으나 $bar값은 여전히 "1000"입니다.
[code php;gutter:false] function foo(&$var) {
$var = &$GLOBALS["baz"];
}

$bar = 1000;
$baz = 91;

foo($bar);
echo "$bar\n"; [/code]
foo 함수를 호출하면 foo 함수에 있는 $var은 $bar와 바인딩되어 있습니다. 그러나 이 때 $var이 $GLOBALS["baz"]와 다시 바인딩할 것입니다. 함수 내에서 참조 메커니즘을 이용하여 호출측 사용범위를 가지고 있는 $bar에 바인딩할 방법이 없습니다. $bar은 함수 foo에서는 사용할 수 없는 변수입니다. $var에 의해 표현되어지기는 하지만 $var은 단지 변수 내용만 가지고 있을 뿐입니다.
< 심볼 테이블 >
scope 변수명 변수값이 저장된
메모리 주소
설명
호출측 $bar 0x6000  
$baz 0x7000  
함수내 $var 0x6000 매개변수가 참조로 넘어갈 때
0x7000 $var = &$GLOBALS["baz"]를 실행한 직후
참조에 의한 객체 전달
생 성된 객체를 참조로 함수 내로 전달할 수 있습니다. 이 때 참조로 넘기지 않고 값으로 넘기게 되면 최초로 생성된 객체의 복사본을 함수 내로 전달하게 되며 이것은 원본과는 다른 별개의 객체입니다. 이것은 마치 앞장에서 $a = new test에 의해 객체가 복사되는냐 아느면 $a = &new test에 의해 객체가 참조되느냐와 같은 원리입니다.
[code php;gutter:false] <?php

class test {
var $mb;

function test($mb="default") {
$this->mb = $mb;
}
}

function foo(&$obj) {
$obj->mb = "in foo()";
}

$a = &new test;
foo($a);
echo $a->mb;

?> [/code]
아 래와 같이 new test로 객체를 생성하자 마자 함수로 전달할 수도 있습니다. 이 예만 가지고는 왜 이렇게 코딩하는지 이해가 되지 않을 것입니다. 이는 참조에 의한 반환과 함께 사용될 때 그 효과가 나타나게 됩니다. 그러니 다음장에 있는 참조에 의한 반환을 참조하세요.
[code php;gutter:false] <?php

class test {
var $mb;

function test($mb="default") {
$this->mb = $mb;
}
}

function foo(&$obj) {
echo $obj->mb;
}

foo(new test);

?> [/code]
$this의 동작 방식
객체 메소드에서 사용하는 $this는 호출측 객체에 대한 참조입니다. 따라서 $this를 가지고 수정한 내용은 호출측 객체의 내용에 그대로 반영됩니다.
[code php;gutter:false] <?php

class test {
var $mb;

function set($mb="default") {
$this->mb = $mb;
}
}

$a = &new test;
$a->set("set()");
echo $a->mb;

?> [/code]
$this가 참조가 아니고 복사였다면 echo $a->mb의 결과는 아무 값도 나타나지 않겠지요.

'phpclass > 객체정보' 카테고리의 다른 글

{참조}5.참조 삭제  (0) 2001.03.02
{참조}4.참조 반환  (0) 2001.03.02
{참조}2.객체생성에서의 참조  (0) 2001.03.02
{참조}1.참조변수의 생성  (0) 2001.03.02
{추상클래스}6.세셔너 확장  (0) 2000.12.28
Posted by 방글24
phpclass/객체정보2001. 3. 2. 14:10
생성된 객체를 복사하기
이 방법은 여러분이 지금까지 사용하였던 방법입니다.
[code php;gutter:false] <?php

class test {
var $mb;

function test($mb="default") {
$this->mb = $mb;
}
}

$a = new test; // 객체 복사
echo $a->mb;

?> [/code]
위의 예를 통해 생성된 객체가 어떤 경로를 통해 $a 변수에 저장되는지 살펴보기로 하겠습니다.
1. new test
이 부분에 의해 클래스 test에 정의된 생성자 test() 함수가 실행됩니다. 생성자 내용이 모두 처리되면 생성자는 현재 생성된 객체를 나타내는 $this라는 특별한 변수를 되돌려 줍니다. 따라서 "new test"를 처리한 후 되돌려 받게 되는 값은 new 연산자에 의해 생성된 객체를 나타내는 $this라는 변수가 됩니다.
2. $a = new test
"new test"가 되돌려 주는 것이 새로 생성된 객체를 나타내는 $this라는 객체변수이므로 "$a = new test"는 "$a = $this"라고 생각할 수 있습니다. 실제로 이렇게 코딩하면 에러가 나겠지요. 왜냐하면 $this라는 변수는 객체 내에서만 사용되는 특수한 변수이므로 객체 외부에서는 절대로 사용할 수 없습니다. 그냥 이해한다는 면에서 "$a = $this"라고 한다면 이것은 일반적으로 알고 있는 $this라는 변수를 새로운 변수 $a에 할당하는 것이며, 결국 새로운 객체변수 $a를 생성되는 동시에 $this의 내용을 복사하게 된다는 것입니다.
< 객체 복사 >
위 그림에서는 멤버변수만 나타내었습니다. 메소드의 표현 방법은 멤버변수와는 전혀 다르기 때문에 여기서 생략하며 이에 대한 자세한 내용은 메뉴 "핍클래스홈 >> 객체에 관련된 정보"에서 "클래스와 인스턴스" 부분을 읽어 보시기 바랍니다.
3. echo $a->mb
복사된 객체 $a를 통해 멤버변수 $mb에 접근합니다.
생성된 객체를 참조하기
위의 소스 코드에서 클래스 정의 부분은 동일하며 아래 부분만 참조에 의해 수정하면 다음과 같습니다.
[code php;gutter:false] $a = &new test; // 객체 참조
echo $a->mb; [/code]
객체 복사와 같은 방법으로 생성된 객체가 어떤 경로를 통해 $a 변수에 저장되는지 살펴보기로 하겠습니다.
1. new test
이 부분은 객체 복사와 동일합니다.
2. $a = &new test
"new test"가 되돌려 주는 것이 새로 생성된 객체를 나타내는 $this라는 객체변수이므로 "$a = &new test"는 "$a = &$this"라고 생각할 수 있습니다. 이것은 앞장에서 살펴보았듯이 "new test"에 의해 생성된 $this라는 객체변수에 대한 별명(참조)을 하나 만드는 것입니다.
< 객체 참조 >
3. echo $a->mb
이 부분은 객체 복사와 동일합니다.
메모리 자원 사용
생성자에 있는 $this의 참조를 사용하기 위해서는 참조할당(reference assignment)을 사용하여야 하며 그렇지 않으면 두 개의 서로 다른 객체를 가지게 될 것입니다.
$this 라는 것은 "new test"를 수행할 때 생성자에서 되돌려 주는 $this를 의미합니다. new 연산자로 생성된 객체를 복사로 받으나 아니면 참조로 받으나 실행에는 전혀 차이가 없습니다. 차이가 있다면 서버 자원(resource)을 얼마나 효율적으로 사용하느냐는 것이지요. 첫번째 처럼 객체를 복사하게 되면 메모리 0x6000에 있는 객체는 페이지가 종료될 때까지 전혀 사용하지도 못하면서 서버 자원만 낭비하고 있는 것이지요. 하지만 객체를 참조하게 되면 생성된 객체를 $b에서 그대로 사용하기 때문에 자원 낭비가 전혀 없게 됩니다.
객체 복사할 때의 메모리
< 심볼 테이블 >
변수명 변수값이 저장된 메모리 주소 설명
$this 0x6000 원본
$a 0x7000 복사

객체 참조할 때의 메모리

< 심볼 테이블 >
변수명 변수값이 저장된 메모리 주소 설명
$this 0x6000 원본
$a 0x6000 참조
메모리 자원을 사용하는데 있어 참조의 장점을 개념상 설명을 하였습니다만 PHP가 실제로 이 개념대로 구현된 것 같지는 않습니다. 정확한 것은 소스를 분석해 보아야 하겠으나 문서상의 설명으로 보면 객체 복사가 오히려 객체 참조보다 수행속도가 미세하나마 빠른 것으로 볼 때 PHP의 참조에 관련된 내부 구현 방식이 개념상 자바나 C++과는 다소 다른 것 같습니다. 따라서 현 시점(PHP 4.0.4 기준)에서 볼 때는 객체 참조가 꼭 요구되지 않는다면 객체 복사를 이용하는 것이 나을 것 같습니다. 그러나 향후 이 문제에 대하여는 PHP가 개선이 있어야 할 것으로 보입니다. 그러니 앞으로 객체 참조가 더 개선될 것을 대비하고 코드의 재사용을 고려하고 객체 복사와 객체 참조의 실행속도가 거의 차이가 없다는 것을 염두에 둔다면 그냥 객체 참조를 사용하는 것이 괜찮으리라 봅니다.
[Zend 엔진 2.0에서의 객체] Zend 엔진 1.0에서는 객체를 전달할 때 기본적으로 복사되어집니다. 그러나 Zend 엔진 2.0부터는 기본적으로 참조로 전달되어 집니다. 즉, 객체를 전달할 때는 참조기호 &가 필요없어진 것이지요. 그러니 PHP3 또는 Zend 엔진 1.0가 탑재된 PHP4로 작성된 문서에서 특별한 문제만 없다면 향후 호환성을 위하여 객체를 전달할 때는 참조기호 &를 사용하지 말기를 바랍니다.

'phpclass > 객체정보' 카테고리의 다른 글

{참조}4.참조 반환  (0) 2001.03.02
{참조}3.참조에 의한 전달  (0) 2001.03.02
{참조}1.참조변수의 생성  (0) 2001.03.02
{추상클래스}6.세셔너 확장  (0) 2000.12.28
{추상클래스}5.세셔너 분석  (0) 2000.12.28
Posted by 방글24
phpclass/객체정보2001. 3. 2. 13:59
C++에서 사용하던 참조(reference)와 같은 기능을 PHP4에서 제공합니다. 참조는 객체를 사용할 때 필수적인 기능이므로 꼭 익혀두시기 바랍니다.
비유에 의한 설명
명선이라는 여자 아이가 살고 있습니다. 그런데 그 아이의 마음씨가 얼마나 좋은지 사람들이 명선이에게 천사라는 별명을 붙여주었습니다. 제가 천사같은 명선이에게 1000원을 주었다고 할 때 명선이에게 1000원을 주었지만 천사에게도 1000원을 준 것과 동일합니다.
< 본명과 별명 >
PHP에서도 이와 같이 특정 변수에 별명을 붙여 사용할 수 있습니다. PHP에서 이와 같이 별명을 만들 수 있는 기능을 참조(reference)라고 하며 PHP4.0.4부터 본격적으로 제공되기 시작했습니다.
< 변수 $a와 참조 $b >
이러한 별명 즉 참조변수를 생성하기 위해서는 아래와 같이 & 심볼을 사용합니다.
[code php;gutter:false] $b = &$a; // 변수 $a의 참조 $b를 생성
$a = 1000; [/code]
참조란 다른 이름을 가지고 동일한 변수에 접근할 수 있도록 하는 것입니다. C 또는 C++의 포인터와는 다르며 C++에서 새로이 추가된 참조와 같이 앞에서 정의된 변수에 대한 이름(변수명)의 대용으로 작용하는 이름입니다. 즉, 앞서 정의된 변수명에 대한 별명입니다. 따라서 이들 둘은 모두 같은 값, 같은 메모리의 위치를 참조합니다.
참조와 복사
참조가 하나의 변수를 두 개의 이름(변수명)으로 불려지는 것인 반면에 복사는 완전히 독립된 두 개의 변수를 만들게 됩니다.
예를 들어 $a으로 하여금 $b 변수를 참조하도록 만든다면 $a와 $b는 서로 다른 이름을 사용하기는 하지만 $a와 $b는 둘 다 동일한 장소(메모리 위치)를 가리키기 때문에 동일한 내용을 다루게 됩니다.
그러나 $a으로 하여금 $c 변수에 복사하게 되면 처음 복사할 때만 그 내용이 같을 뿐이며 이 후에 $a와 $c는 전혀 관계없이 동작하는 별개의 변수가 됩니다.
[code php;gutter:false] $a = 1000; // 변수 $a의 생성
$b = &$a; // $b는 $a의 참조(별명)
$c = $a; // $c는 $a의 복사 [/code]
< 참조와 복사 >
변수명를 관리하는 심볼 테이블과 변수값이 저장되어 있는 메모리 상태를 살펴보면 다음과 같습니다. 여기서 표현된 것은 설명을 위해 개념적으로 나타낸 것이며 정확한 것은 아닙니다.
< 심볼 테이블 >
변수명 변수값이 저장된 메모리 주소 설명
$a 0x6000 원본
$b 0x6000 참조
$c 0x7000 복사
참조와 포인터
C 또는 C++에서 자주 보게 되는 포인터와 비교해보죠. 사실 참조로 구현할 수 있는 것은 포인터로 모두 구현할 수 있습니다. 그러나 양쪽이 모두 동일한 효과를 얻더라도 소스코드의 가독성를 보면 참조가 훨씬 명료합니다. PHP가 포인터를 지원하지 않으므로 여기서 비교할 필요가 없을 지도 모르겠으나 그냥 참고삼아 보시기 바랍니다. 만약 PHP에서 포인터를 지원한다면 위의 심볼 테이블에서 메모리 주소 0x6000 또는 0x7000 이라는 숫자를 직접 얻을 수 있겠지요.
아래 예는 C++로 작성된 코드로 함수의 매개변수로 전달된 두 변수를 교환하는 방법입니다.
[code c;gutter:false] void swap(int & a, int & b) { // 참조를 사용
int temp;

temp = a; // 변수의 값으로 a, b를 사용
a = b;
b = temp;
}

void swap(int * pa, int * pb) { // 포인터를 사용
int temp;

temp = *pa; // 변수의 값으로 *pa, *pb를 사용
*pa = *pb;
*pb = temp;
} [/code]
위에서 보는 바와 같이 참조를 사용하면 포인터를 사용할 때보다 코드를 훨씬 쉽게 이해할 수 있습니다. 포인터가 일반적으로 훨씬 강력하고 폭넓은 능력을 발휘하기는 하지만 잘못 사용하면 시스템을 불안하게 하기 때문에 안정성이 우선인 웹프로그래밍 언어에서 포인터를 지원하기는 어려울 것입니다. 하지만 원본을 사용범위(scope)가 다른 곳에서 또는 다른 이름으로 안전하고, 편하게 다루게 해주는 참조가 있기 때문에 개발자는 포인터없이도 별 어려움없이 원하는 기능을 구현할 수 있을 것입니다.
자바에서의 객체 참조
자바에서는 PHP 또는 C++에서와는 달리 객체를 변수에 할당하거나, 객체를 매개변수로 메소드에 전달할 때, 전달되는 것은 이러한 객체의 참조(레퍼런스)이지 객체의 복사본이 아닙니다.
[code java;gutter:false] import java.awt.Point;

class ReferencesTest {
public static void main (String args[]) {
Point pt1, pt2;
pt1 = new Point(100, 100);
pt2 = pt1;

pt1.x = 200;
pt1.y = 200;
system.out.println("Point1: " + pt1.x + ", " + pt1.y);
system.out.println("Point2: " + pt2.x + ", " + pt2.y);
}
} [/code]
출력결과는 아래와 같습니다.
Point1: 200, 200
Point2: 200, 200
pt2 의 x와 y 인스턴스 변수 또한 바뀌었습니다. pt1의 값을 pt2로 할당했을 때, 정확히 말하자면 pt2로부터 pt1도 똑같이 참조하는 레퍼런스를 생성한 것입니다. pt2가 참조하는 객체를 바꾸게 되면, pt1이 가리키는 객체 또한 바뀌게 됩니다. 이들은 같은 객체를 참조하기 때문입니다.
만일 pt1과 pt2가 각각의 분리된 객체를 가리키게 하기를 원한다면 pt2 = pt1 대신에 pt2 = new Point(100, 100)을 사용하여야 합니다.
함수의 매개변수로 사용되는 참조
참조를 자주 사용하는 것 중에 하나가 함수에서의 매개변수입니다. 참조를 매개변수로 사용하면 그 함수는 복사본 대신에 자료의 원본을 가지고 작업을 합니다. 매개변수값이 큰 사이즈의 문자열 또는 객체일 때 복사본 가지고 작업한다면 우선 복사하는데 많은 시간이 소요될 것입니다. 또 작업한 내용을 되돌려 주어야 한다면 돌려주는데 또 시간이 많이 소요될 것입니다. 이럴 때는 처음부터 원본가지고 작업하면 유리하겠지요. 참조 기능 중 유일하게 이 부분만(일부이기는 하지만) PHP3에서도 제공되어 왔습니다. 자세한 것은 "참조에 의한 전달"을 보시기 바랍니다.
PHP에서 지원하는 참조 관련 기능
참조에 의한 함수 호출(call by reference)를 제외한 대부분의 기능은 PHP 4.0.4부터 가능합니다. 이러한 참조기능 - 참조변수 생성, 참조에 의한 함수호출 및 반환 - 은 C++의 참조를 모델로 구현되어 있습니다. 따라서 C++에서 참조를 사용하시던 분은 별 어려움없이 PHP 참조를 사용하시리라 봅니다.

'phpclass > 객체정보' 카테고리의 다른 글

{참조}3.참조에 의한 전달  (0) 2001.03.02
{참조}2.객체생성에서의 참조  (0) 2001.03.02
{추상클래스}6.세셔너 확장  (0) 2000.12.28
{추상클래스}5.세셔너 분석  (0) 2000.12.28
{추상클래스}4.PHP  (0) 2000.12.28
Posted by 방글24
phpsource/회원인증2001. 2. 22. 15:06
제공되는 메소드
메소드 버전 기능
생성자 0.0.1 쿠커의 객체화, 초기값 설정
check 0.0.1 인증회원에게 현재페이지의 접근을 허용할 것인가를 확인
name 0.0.1 사용자명 및 암호를 저장하는 쿠키명을 획득/설정
logout 0.0.1 로그아웃. 모든 사용자 정보를 삭제
메소드 사용법
생성자 permCook([, string err [, bool path]])
[code php;gutter:false] $perm = new permCook("회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요."); [/code]
생성자에서는 허용되지 않은 방문자가 접근하였을 때 보여주는 에러메시지 err와 인증창에서 디렉토리 인증을 수행하였을 때 필요한 path 매개변수를 지정합니다.
허용되지 않은 방문자가 접근하면 check() 함수를 실행할 때 아래와 같은 에러 양식이 나타납니다. 이 에러 양식에 나타낼 문자열이 첫번째 매개변수 err입니다.
< 에러 출력 화면 >
두번째 파리미터는 쿠키인증 클래스에서와 마찬가지로 디렉토리별로 인증을 수행할 수 있도록 해줍니다. 이 매개변수는 쿠키인증 클래스에서 지정된 값과 동일한 값으로 지정하여야 합니다.
[code php;gutter:false] $perm = new permCook("회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요." , true); [/code]
생성자의 첫번째 매개변수는 또 다른 중요한 기능을 가지고 있습니다. 이를 지정하면 에러 화면에 나타날 문자열이 되지만 이를 생략하거나 널문자를 넘기게 되면 check() 함수를 수행할 때 에러화면이 나타나지 않습니다. 에러 화면은 생성자의 첫번째 매개변수에 널문자가 아닌 문자를 지정하였을 때만 나타나게 되어 있습니다. 이를 지정하지 않으면 어떠한 에러화면도 나타나지 않습니다.
첫번째 매개변수를 지정하게 되면 check() 함수를 실행하는 중에 에러가 발생하면 이에 상당하는 각종 에러 화면을 알아서 보여주지만 대신에 제어권을 사용자에게 넘기지 않습니다. 즉 에러 화면을 보여주는 즉시 실행을 중지합니다. 그러나 지정하지 않게 되면 에러 화면을 보여주지 않지만 대신에 실행을 중지하지 않고 제어권을 사용자에게 넘겨줍니다. 제어권을 사용자에게 넘기면서 현재 상태를 리턴값으로 되돌려 줍니다. 따라서 사용자는 이 값을 확인하여 적절한 처리를 해 주어야 인증 처리에 문제가 발생하지 않습니다. 적절히 처리하지 못하면 문제가 발생하지요. check() 함수에서 되돌려 주는 상태값에 대하여는 check() 함수를 참조바랍니다.
int check([string permission_type, string permission_user])
반환되는 상태를 보면 다음과 같습니다.
상태값 설명
0 현재 페이지에 대하여 접근을 허용함
1 사용자 정보가 없음. 현재 페이지에 접근하기 위해서는 먼저 로그인을 할 것
2 특정회원에게만 허용된 페이지에 호용되지 않은 회원이 접근하려고 함
3 정의되지 않은 퍼미션 등급을 지정하였음
아래는 생성자의 첫번째 매개변수를 지정하였을 때의 예입니다.
[code php;gutter:false] <?php require "./cooker/class.cooker.php"; // 쿠커 require "./authcook/class.permcook.php"; // 쿠키퍼미션 클래스 $perm = new permCook("회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요."); $permission_user = "user1"; $permission_type = "owner"; $perm->check($permission_type, $permission_user); // // 페이지 퍼미션을 통과하였음 // . . . ?> [/code]
아래는 생성자의 첫번째 매개변수를 지정하지 않았을 때의 예입니다.
[code php;gutter:false] <?php require "./cooker/class.cooker.php"; // 쿠커 require "./authcook/class.permcook.php"; // 쿠키퍼미션 클래스 $perm = new permCook; $permission_user = "user1"; $permission_type = "owner"; $status = $perm->check($permission_type, $permission_user); if ($status) { switch ($status) { case 1: // 사용자 정보가 없음 echo "먼저 로그인을 하세요.\n"; break; case 2: // 특정 회원 전용 페이지 echo "회원님은 이 페이지를 이용할 수 없습니다.\n"; break; case 3: // 정의되지 않은 퍼미션 등급 echo "정의되지 않은 퍼미션 등급을 지정하였습니다. 소스코드를 확인하세요.\n"; break; } exit; } // // 페이지 퍼미션을 통과하였음 // . . . ?> [/code]
위에서와 같이 $permission_type 을 "owner"으로 설정하고, $permission_user에 특정회원ID를 설정한 후 $perm->check($permission_type, $permission_user) 함수로 확인하게 되면 쿠키에 기록된 회원ID와 $permission_user가 동일한 경우에만 페이지 접근을 허용하게 됩니다. 회원인증을 통과한 모든 회원이 볼 수 있도록 하려면 $permission_type와 $permission_user를 지정하지 않아도 되며 $perm->check() 함수를 인수없이 실행하면 로그인 과정에서 인증을 통과한 방문자는 모두 현재 페이지를 볼 수 있습니다.
string name([string newname])
쿠커에서 사용되는 쿠키명(cookie name)을 얻거나 새로운 쿠키명으로 설정할 때 사용할 수 있습니다. 새로운 쿠키명을 설정할 때는 반드시 start() 함수보다 앞서 수행하여야 합니다. 쿠커는 기본적으로 쿠키명을 "PHP_AUTH_DATA"로 설정되어 있습니다. 보안을 위해 주기적으로 변경해주는 것이 바람직합니다.
[code php;gutter:false] $auth = new authCook("회원 확인 영역"); $auth->name("NEW_COOKIE_NAME"); $status = $auth->start(); // 인증창을 띄운다. echo "현재 설정되어 있는 쿠키명은 ".$auth->name()."입니다.\n"; [/code]
void logout(void)
쿠커에 저장된 모든 사용자 정보를 삭제합니다. 아울러 쿠키파일도 삭제합니다. 이 함수는 자바스크립트로 구현되어 있으므로 어느 위치에서나 사용할 수 있습니다.
[code php;gutter:false] <?php require "./cooker/class.cooker.php"; // 쿠커 require "./authcook/class.permcook.php"; // 쿠키퍼미션 클래스 $perm = new permCook("회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요."); $perm->check(); // // 페이지 퍼미션을 통과하였음 // $perm->logout(); echo "<A href=login.php3>로그인</A>"; ?> [/code]

Posted by 방글24
phpsource/회원인증2001. 2. 22. 15:00
제공되는 메소드
메소드 버전 기능
생성자 0.0.1 쿠커의 객체화, 초기값 설정
start 0.0.1 사용자명 및 암호를 입력받아 처리함
name 0.0.1 사용자명 및 암호를 저장하는 쿠키명을 획득/설정
gc_maxlifetime 0.0.1 서버상에서 확인하는 쿠키의 생존시간 획득/설정
메소드 사용법
생성자 authCook([string realm [, string err [, bool path]]])
[code php;gutter:false] $auth = new authCook("회원 확인", "회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요."); [/code]
위에서와 같이 클래스 authCook을 객체화하게 되면 start() 함수를 실행할 때 아래와 같이 사용자명 및 암호를 입력받을 수 있는 양식이 나타납니다. 이 화면에서 영역이라고 표시되는 부분에 나타날 문자열이 첫번째 매개변수인 realm입니다.
< 인증창 >
위의 입력양식에서 세번 연속하여 사용자명과 암호를 모두 입력하지 않고 서브밋하면 아래와 같은 에러 양식이 나타납니다. 이 에러 양식에 나타낼 문자열이 두번째 매개변수인 err입니다.
< 에러 출력 화면 >
세번째 파리미터는 "HTTP 인증"에서는 생소한 부분입니다. "HTTP 인증"에서는 한 번 인증하면 모든 디렉토리에서 통용되지요. 이는 반대로 말한다면 디렉토리별로 인증이 어렵다는 것입니다. 그래서 많은 분들이 웹서버 아파치를 통해(.htaccess 파일을 통해) 디렉토리 별로 인증을 수행하는 것을 볼 수 있습니다. 세번째 매개변수가 이와 같이 디렉토리별로 인증을 수행할 수 있도록 쿠키인증 클래스의 쿠키 매개변수 path를 지정하는 역할을 합니다. 생략하면(기본값으로 false로 설정되어 있음) "HTTP 인증"과 마찬가지로 모든 디렉토리에 대하여 한번만 인증을 수행하게 됩니다. 디렉토리별로 인증하고 싶으면 세번째 매개변수의 값을 true라고 지정하시기 바랍니다.
[code php;gutter:false] $auth = new authCook("회원 확인 영역", "회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요.", true); [/code]
생성자의 두번째 매개변수는 또 다른 중요한 기능을 가지고 있습니다. 이를 지정하면 에러 화면에 나타날 문자열이 되지만 이를 생략하거나 널문자를 넘기게 되면 start() 함수를 수행할 때 에러화면이 나타나지 않습니다. 인증창에서 사용자 정보를 입력하는 과정에서는 위에서와 같은 에러 화면말고도 여러가지 에러 화면이 존재합니다. 이미 사용자 정보를 입력하였는데 다시 입력을 요구할 때 발생하는 에러 메시지, 브라우저에 쿠키를 사용할 수 없도록 설정되어 있다는 에러 메시지 등을 위한 에러 화면이 있습니다. 그러나 이러한 에러 화면은 생성자의 두번째 매개변수에 널문자가 아닌 문자를 지정하였을 때만 나타나게 되어 있습니다. 이를 지정하지 않으면 어떠한 에러화면도 나타나지 않습니다.
생성자의 두번째 매개변수를 다른 관점에서 살펴보면, 이를 지정하게 되면 start() 함수를 실행하는 중에 에러가 발생하면 이에 상당하는 각종 에러 화면을 알아서 보여주지만 대신에 제어권을 사용자에게 넘기지 않습니다. 즉 에러 화면을 보여주는 즉시 실행을 중지합니다. 그러나 지정하지 않게 되면 에러 화면을 보여주지 않지만 대신에 실행을 중지하지 않고 제어권을 사용자에게 넘겨줍니다. 제어권을 사용자에게 넘기면서 현재 상태를 리턴값으로 되돌려 줍니다. 따라서 사용자는 이 값을 확인하여 적절한 처리를 해 주어야 인증 처리에 문제가 발생하지 않습니다. 적절히 처리하지 못하면 문제가 발생하지요. start() 함수에서 되돌려 주는 상태값에 대하여는 start() 함수를 참조바랍니다.
int start(void)
사용자 정보를 입력받는 인증창은 별도의 화면에 나타냅니다.
반환되는 상태를 보면 다음과 같습니다.
상태값 설명
0 인증창에서 사용자 이름 및 암호를 정상적으로 입력함
1 웹브라우저의 쿠키 설정이 OFF로 되어 있어 쿠키를 사용할 수 없음
2 인증창에서 사용자 이름 및 암호를 3번 이상 틀리게 입력함
3 이미 로그인 중임. 다른 ID로 인증하려면 먼저 로그아웃하기 바람.
4 인증창이 나타나 있으므로 인증창을 통해 사용자 이름 및 암호를 입력하기 바람
[code php;gutter:false] $auth = new authCook("회원 확인 영역"); $status = $auth->start(); // 인증창을 띄운다. if ($status) { switch ($status) { case 1: // 쿠키 설정이 안됨 echo "웹브라우저에 쿠키를 사용할 수 있도록 설정하세요.\n"; break; case 2: // 회원정보 입력을 3번 이상 틀림 echo "회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요.\n"; break; case 3: // 이미 로그인중 echo "님은 이미 로그인중입니다." ." 다른 ID로 로그인하려면 먼저 로그아웃을 하세요.\n"; break; case 4: // 로그인창 출력중 echo "먼저 로그인창에서 회원정보를 입력하세요.\n"; break; } exit; } // // 쿠키 인증창 통과하였음 // 회원정보테이블과 입력된 회원정보를 비교하여야 함 // . . . [/code]
string name([string newname])
쿠커에서 사용되는 쿠키명(cookie name)을 얻거나 새로운 쿠키명으로 설정할 때 사용할 수 있습니다. 새로운 쿠키명을 설정할 때는 반드시 start() 함수보다 앞서 수행하여야 합니다. 쿠커는 기본적으로 쿠키명을 "PHP_AUTH_DATA"로 설정되어 있습니다. 보안을 위해 주기적으로 변경해주는 것이 바람직합니다.
[code php;gutter:false] $auth = new authCook("회원 확인 영역"); $auth->name("NEW_COOKIE_NAME"); $status = $auth->start(); // 인증창을 띄운다. echo "현재 설정되어 있는 쿠키명은 ".$auth->name()."입니다.\n"; [/code]
void gc_maxlifetime(int lifetime), int gc_maxlifetime(void)
gc_maxlifetime() 함수는 서버에서 쿠키의 유효기간을 확인할 수 있도록 그 시간을 설정하거나 획득하기 위한 함수입니다.
[code php;gutter:false] $auth->gc_maxlifetime(600); //서버에서의 쿠키지속시간(초단위/10분) $auth->start(); [/code]
쿠키가 생성된 후 10분이 지나면 서버에서 gc_maxlifetime(600)에 의해 쿠키정보를 임의로 삭제하게 됩니다. 이러한 기능은 시간에 의한 자동로그아웃을 구현할 때 유용하게 사용될 수 있을 것입니다. 또 한가지는 gc_maxlifetime() 함수로 유효기간을 설정하는 것은 쿠키를 처음 생성할 때 한번만 수행하면 됩니다. 이 함수는 실제로는 쿠커에서 모두 담당하기 때문에 로인한 후 페이지 퍼미션에서는 이 함수를 수행하지 않더라도 이미 쿠커에 의해 계속 유효하게 됩니다. 따라서 쿠키퍼미션 클래스에서는 이 함수가 제공되지 않습니다.
gc_maxlifetime() 함수에서 설정할 때는 start() 함수 전에 수행하여야 합니다.

Posted by 방글24
phpsource/회원인증2001. 2. 22. 14:55
"PHP를 이용한 HTTP 인증(HTTP authentication with PHP)"에 대한 것은 잘 알고 있으리라 생각합니다. 쿠키인증 클래스는 "PHP를 이용한 HTTP 인증"를 모델링하여 작성된 클래스입니다. "PHP를 이용한 HTTP 인증"에서 수행이 어려운 로그아웃 처리를 쉽게 수행할 수 있는 기능을 가지게 될 것입니다. 마지막 접속 후 지정된 시간(기본값은 24분)이 지나면 자동으로 로그아웃하는 기능도 가지게 될 것입니다.
쿠키에 대한 일반적인 정보는 상단메뉴의 "쿠커"정보를 참조바랍니다.
활용 예제의 구성
소스코드의 전체구성을 살펴보면 아래와 같습니다.
1. 쿠키 관리용 클래스
▶ 쿠커(class.cooker.php)
2. 쿠키인증클래스
▶ 쿠키인증 클래스(class.authcook.php)
▶ 쿠키퍼미션 클래스(class.permcook.php)
3. 회원정보 관리용 클래스
▶ 회원정보 클래스(class.member.php)
4. 실험용 예제
▶ 로그인 페이지(login.php3)
▶ 회원전용 홈페이지(home.php3)
▶ 회원#1 페이지(member1.php3)
▶ 회원#2 페이지(member2.php3)
▶ 회원#3 페이지(member3.php3)
▶ 로그아웃 페이지(logout.php3)
< 예제 구성 >
쿠커(class.cooker.php)
쿠커(Cooker) 및 쿠키 암호화 클래스에 대한 정보는 메뉴 "후키라이브러리 >> 쿠커"를 참조바랍니다.
쿠키인증 클래스(class.authcook.php)
쿠키인증 클래스는 "PHP를 이용한 HTTP 인증"를 모델링하여 작성된 클래스입니다. 쿠키인증 클래스에서 쿠키를 다루기 위해 앞서 공개된 쿠커(Cooker)와 쿠키 암호화 클래스를 이용하게 됩니다. 그러니 먼저 쿠커에 대한 자료를 참조하기 바랍니다. "PHP를 이용한 HTTP 인증"은 아래와 같이 작성되는 것이 보통입니다.
[code php;gutter:false] <?php function authentication() { Header("WWW-authenticate: basic realm=\"회원 확인\""); Header("HTTP/1.0 401 Unauthorized"); echo "회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요."; exit; } if (!$PHP_AUTH_USER || !$PHP_AUTH_PW) { // // 인증창에 값을 입력하지 않은 경우 다시 인증창을 띄운다. // authentication(); exit; } // // 인증창 통과하였음 // 여기에서 회원 인증을 한다. // ...... 디비 등을 이용하여 회원 인증을 위한 소스 코드 삽입 ...... if (회원인증에 실패했으면?) { authentication(); // 다시 인증창을 띄운다. exit; } // // 회원인증에 성공함 // echo "<META http-equiv='Refresh' content='0; URL=home.php3'>"; ?> [/code]
쿠키인증 클래스를 이용하여 위와 동일한(?) 기능을 할 수 있도록 작성하면 다음과 같습니다.
[code php;gutter:false] <?php require "./cooker/class.cooker.php"; // 쿠커 require "./authcook/class.authcook.php"; // 쿠키인증 클래스 $auth = new authCook("회원 확인", "회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요."); $auth->start(); // 인증창을 띄운다. // // 인증창 통과하였음 // 여기에서 회원 인증을 한다. // ...... 디비 등을 이용하여 회원 인증을 위한 소스 코드 삽입 ...... if (회원인증에 실패했으면?) { $auth->start(); // 다시 인증창을 띄운다. exit; } // // 회원인증에 성공함 // echo "<META http-equiv='Refresh' content='0; URL=home.php3'>"; ?> [/code]
쿠키퍼미션 클래스(class.permcook.php)
일단 회원인증에 성공하게 되면 쿠커(Cooker)에 의해 클라이언트 쿠키영역에 정해진 양식대로 회원정보가 기록되며, 각 회원 전용 페이지에서는 기록된 회원정보를 가지고 페이지 접근 허용 여부를 결정하게 됩니다. 이를 위해 작성된 클래스가 쿠키퍼미션 클래스입니다.
[code php;gutter:false] <?php require "./cooker/class.cooker.php"; // 쿠커 require "./authcook/class.permcook.php"; // 쿠키퍼미션 클래스 $perm = new permCook("회원전용 서비스를 받으시려면 먼저 회원으로 가입하세요."); $permission_user = "user1"; $permission_type = "owner"; $perm->check($permission_type, $permission_user); // // 페이지 퍼미션을 통과하였음 // . . . ?> [/code]
회원정보 클래스(class.member.php)
회원정보 클래스의 목적은 보통 데이터베이스에 기록되어 있는 회원정보와 로그인 과정에서 취득하게 되는 회원ID와 패스워드를 비교하여 방문자가 등록된 회원인가를 확인하는 것을 도와주기 위한 것입니다. 그러나 제가 공개한 본 클래스는 쿠키인증 클래스를 실험하기 위해 임시로 작성되어 있으며 여기서는 회원에 대한 정보를 데이터베이스가 아닌 일반 배열에 담았습니다. 따라서 이 클래스를 실전에서 사용하기 위해서는 소스 코드를 대폭 수정하여 데이터베이스를 이용하여 회원정보를 관리할 수 있도록 하여야 할 것입니다. 그러니 이 클래스는 쿠키인증 클래스의 실험용 이상의 의미를 두지 마시기 바랍니다.
페이지 구성 및 회원별 접근 제한
예제 프로그램에서는 페이지 #1, #2, #3는 퍼미션 등급이 "owner"으로 설정되어 있고, 홈페이지와 로그아웃 페이지는 퍼미션 등급이 설정되어 있지 않습니다.
페이지 구성 접근이 허용된 회원
로그인 페이지 모든 방문자
홈페이지 로그인한 모든 회원
페이지 #1 로그인한 "user1" 회원
페이지 #2 로그인한 "user2" 회원
페이지 #3 로그인한 "user3" 회원
로그아웃 페이지 로그인한 모든 회원
회원정보 클래스에 저장된 회원정보
위에서 언급한 바와 같이 회원정보가 배열의 형태로 저장되어 있습니다.
사용자 이름 암호
user1 test
user2 test
user3 test

Posted by 방글24

RFC2109 - HTTP State Management Mechanism

Network Working Group                                         D. Kristol
Request for Comments: 2109 Bell Laboratories, Lucent Technologies
Category: Standards Track L. Montulli
Netscape Communications
February 1997

HTTP State Management Mechanism

Status of this Memo

This document specifies an Internet standards track protocol for the
Internet community, and requests discussion and suggestions for
improvements. Please refer to the current edition of the "Internet
Official Protocol Standards" (STD 1) for the standardization state
and status of this protocol. Distribution of this memo is unlimited.

1. ABSTRACT

This document specifies a way to create a stateful session with HTTP
requests and responses. It describes two new headers, Cookie and
Set-Cookie, which carry state information between participating
origin servers and user agents. The method described here differs
from Netscape's Cookie proposal, but it can interoperate with
HTTP/1.0 user agents that use Netscape's method. (See the HISTORICAL
section.)

2. TERMINOLOGY

The terms user agent, client, server, proxy, and origin server have
the same meaning as in the HTTP/1.0 specification.

Fully-qualified host name (FQHN) means either the fully-qualified
domain name (FQDN) of a host (i.e., a completely specified domain
name ending in a top-level domain such as .com or .uk), or the
numeric Internet Protocol (IP) address of a host. The fully
qualified domain name is preferred; use of numeric IP addresses is
strongly discouraged.

The terms request-host and request-URI refer to the values the client
would send to the server as, respectively, the host (but not port)
and abs_path portions of the absoluteURI (http_URL) of the HTTP
request line. Note that request-host must be a FQHN.

Hosts names can be specified either as an IP address or a FQHN
string. Sometimes we compare one host name with another. Host A's
name domain-matches host B's if

* both host names are IP addresses and their host name strings match
exactly; or

* both host names are FQDN strings and their host name strings match
exactly; or

* A is a FQDN string and has the form NB, where N is a non-empty name
string, B has the form .B', and B' is a FQDN string. (So, x.y.com
domain-matches .y.com but not y.com.)

Note that domain-match is not a commutative operation: a.b.c.com
domain-matches .c.com, but not the reverse.

Because it was used in Netscape's original implementation of state
management, we will use the term cookie to refer to the state
information that passes between an origin server and user agent, and
that gets stored by the user agent.

3. STATE AND SESSIONS

This document describes a way to create stateful sessions with HTTP
requests and responses. Currently, HTTP servers respond to each
client request without relating that request to previous or
subsequent requests; the technique allows clients and servers that
wish to exchange state information to place HTTP requests and
responses within a larger context, which we term a "session". This
context might be used to create, for example, a "shopping cart", in
which user selections can be aggregated before purchase, or a
magazine browsing system, in which a user's previous reading affects
which offerings are presented.

There are, of course, many different potential contexts and thus many
different potential types of session. The designers' paradigm for
sessions created by the exchange of cookies has these key attributes:

1. Each session has a beginning and an end.

2. Each session is relatively short-lived.

3. Either the user agent or the origin server may terminate a
session.

4. The session is implicit in the exchange of state information.

4. OUTLINE

We outline here a way for an origin server to send state information
to the user agent, and for the user agent to return the state
information to the origin server. The goal is to have a minimal
impact on HTTP and user agents. Only origin servers that need to
maintain sessions would suffer any significant impact, and that
impact can largely be confined to Common Gateway Interface (CGI)
programs, unless the server provides more sophisticated state
management support. (See Implementation Considerations, below.)

4.1 Syntax: General

The two state management headers, Set-Cookie and Cookie, have common
syntactic properties involving attribute-value pairs. The following
grammar uses the notation, and tokens DIGIT (decimal digits) and
token (informally, a sequence of non-special, non-white space
characters) from the HTTP/1.1 specification [RFC 2068] to describe
their syntax.

av-pairs = av-pair *(";" av-pair)
av-pair = attr ["=" value] ; optional value
attr = token
value = word
word = token | quoted-string

Attributes (names) (attr) are case-insensitive. White space is
permitted between tokens. Note that while the above syntax
description shows value as optional, most attrs require them.

NOTE: The syntax above allows whitespace between the attribute and
the = sign.

4.2 Origin Server Role

4.2.1 General

The origin server initiates a session, if it so desires. (Note that
"session" here does not refer to a persistent network connection but
to a logical session created from HTTP requests and responses. The
presence or absence of a persistent connection should have no effect
on the use of cookie-derived sessions). To initiate a session, the
origin server returns an extra response header to the client, Set-
Cookie. (The details follow later.)

A user agent returns a Cookie request header (see below) to the
origin server if it chooses to continue a session. The origin server
may ignore it or use it to determine the current state of the

session. It may send back to the client a Set-Cookie response header
with the same or different information, or it may send no Set-Cookie
header at all. The origin server effectively ends a session by
sending the client a Set-Cookie header with Max-Age=0.

Servers may return a Set-Cookie response headers with any response.
User agents should send Cookie request headers, subject to other
rules detailed below, with every request.

An origin server may include multiple Set-Cookie headers in a
response. Note that an intervening gateway could fold multiple such
headers into a single header.

4.2.2 Set-Cookie Syntax

The syntax for the Set-Cookie response header is

set-cookie = "Set-Cookie:" cookies
cookies = 1#cookie
cookie = NAME "=" VALUE *(";" cookie-av)
NAME = attr
VALUE = value
cookie-av = "Comment" "=" value
| "Domain" "=" value
| "Max-Age" "=" value
| "Path" "=" value
| "Secure"
| "Version" "=" 1*DIGIT

Informally, the Set-Cookie response header comprises the token Set-
Cookie:, followed by a comma-separated list of one or more cookies.
Each cookie begins with a NAME=VALUE pair, followed by zero or more
semi-colon-separated attribute-value pairs. The syntax for
attribute-value pairs was shown earlier. The specific attributes and
the semantics of their values follows. The NAME=VALUE attribute-
value pair must come first in each cookie. The others, if present,
can occur in any order. If an attribute appears more than once in a
cookie, the behavior is undefined.

NAME=VALUE
Required. The name of the state information ("cookie") is NAME,
and its value is VALUE. NAMEs that begin with $ are reserved for
other uses and must not be used by applications.

The VALUE is opaque to the user agent and may be anything the
origin server chooses to send, possibly in a server-selected
printable ASCII encoding. "Opaque" implies that the content is of
interest and relevance only to the origin server. The content
may, in fact, be readable by anyone that examines the Set-Cookie
header.

Comment=comment
Optional. Because cookies can contain private information about a
user, the Cookie attribute allows an origin server to document its
intended use of a cookie. The user can inspect the information to
decide whether to initiate or continue a session with this cookie.

Domain=domain
Optional. The Domain attribute specifies the domain for which the
cookie is valid. An explicitly specified domain must always start
with a dot.

Max-Age=delta-seconds
Optional. The Max-Age attribute defines the lifetime of the
cookie, in seconds. The delta-seconds value is a decimal non-
negative integer. After delta-seconds seconds elapse, the client
should discard the cookie. A value of zero means the cookie
should be discarded immediately.

Path=path
Optional. The Path attribute specifies the subset of URLs to
which this cookie applies.

Secure
Optional. The Secure attribute (with no value) directs the user
agent to use only (unspecified) secure means to contact the origin
server whenever it sends back this cookie.

The user agent (possibly under the user's control) may determine
what level of security it considers appropriate for "secure"
cookies. The Secure attribute should be considered security
advice from the server to the user agent, indicating that it is in
the session's interest to protect the cookie contents.

Version=version
Required. The Version attribute, a decimal integer, identifies to
which version of the state management specification the cookie
conforms. For this specification, Version=1 applies.

4.2.3 Controlling Caching

An origin server must be cognizant of the effect of possible caching
of both the returned resource and the Set-Cookie header. Caching
"public" documents is desirable. For example, if the origin server
wants to use a public document such as a "front door" page as a
sentinel to indicate the beginning of a session for which a Set-
Cookie response header must be generated, the page should be stored
in caches "pre-expired" so that the origin server will see further
requests. "Private documents", for example those that contain
information strictly private to a session, should not be cached in
shared caches.

If the cookie is intended for use by a single user, the Set-cookie
header should not be cached. A Set-cookie header that is intended to
be shared by multiple users may be cached.

The origin server should send the following additional HTTP/1.1
response headers, depending on circumstances:

* To suppress caching of the Set-Cookie header: Cache-control: no-
cache="set-cookie".

and one of the following:

* To suppress caching of a private document in shared caches: Cache-
control: private.

* To allow caching of a document and require that it be validated
before returning it to the client: Cache-control: must-revalidate.

* To allow caching of a document, but to require that proxy caches
(not user agent caches) validate it before returning it to the
client: Cache-control: proxy-revalidate.

* To allow caching of a document and request that it be validated
before returning it to the client (by "pre-expiring" it):
Cache-control: max-age=0. Not all caches will revalidate the
document in every case.

HTTP/1.1 servers must send Expires: old-date (where old-date is a
date long in the past) on responses containing Set-Cookie response
headers unless they know for certain (by out of band means) that
there are no downsteam HTTP/1.0 proxies. HTTP/1.1 servers may send
other Cache-Control directives that permit caching by HTTP/1.1
proxies in addition to the Expires: old-date directive; the Cache-
Control directive will override the Expires: old-date for HTTP/1.1
proxies.

4.3 User Agent Role

4.3.1 Interpreting Set-Cookie

The user agent keeps separate track of state information that arrives
via Set-Cookie response headers from each origin server (as
distinguished by name or IP address and port). The user agent
applies these defaults for optional attributes that are missing:

VersionDefaults to "old cookie" behavior as originally specified by
Netscape. See the HISTORICAL section.

Domain Defaults to the request-host. (Note that there is no dot at
the beginning of request-host.)

Max-AgeThe default behavior is to discard the cookie when the user
agent exits.

Path Defaults to the path of the request URL that generated the
Set-Cookie response, up to, but not including, the
right-most /.

Secure If absent, the user agent may send the cookie over an
insecure channel.

4.3.2 Rejecting Cookies

To prevent possible security or privacy violations, a user agent
rejects a cookie (shall not store its information) if any of the
following is true:

* The value for the Path attribute is not a prefix of the request-
URI.

* The value for the Domain attribute contains no embedded dots or
does not start with a dot.

* The value for the request-host does not domain-match the Domain
attribute.

* The request-host is a FQDN (not IP address) and has the form HD,
where D is the value of the Domain attribute, and H is a string
that contains one or more dots.

Examples:

* A Set-Cookie from request-host y.x.foo.com for Domain=.foo.com
would be rejected, because H is y.x and contains a dot.

* A Set-Cookie from request-host x.foo.com for Domain=.foo.com would
be accepted.

* A Set-Cookie with Domain=.com or Domain=.com., will always be
rejected, because there is no embedded dot.

* A Set-Cookie with Domain=ajax.com will be rejected because the
value for Domain does not begin with a dot.

4.3.3 Cookie Management

If a user agent receives a Set-Cookie response header whose NAME is
the same as a pre-existing cookie, and whose Domain and Path
attribute values exactly (string) match those of a pre-existing
cookie, the new cookie supersedes the old. However, if the Set-
Cookie has a value for Max-Age of zero, the (old and new) cookie is
discarded. Otherwise cookies accumulate until they expire (resources
permitting), at which time they are discarded.

Because user agents have finite space in which to store cookies, they
may also discard older cookies to make space for newer ones, using,
for example, a least-recently-used algorithm, along with constraints
on the maximum number of cookies that each origin server may set.

If a Set-Cookie response header includes a Comment attribute, the
user agent should store that information in a human-readable form
with the cookie and should display the comment text as part of a
cookie inspection user interface.

User agents should allow the user to control cookie destruction. An
infrequently-used cookie may function as a "preferences file" for
network applications, and a user may wish to keep it even if it is
the least-recently-used cookie. One possible implementation would be
an interface that allows the permanent storage of a cookie through a
checkbox (or, conversely, its immediate destruction).

Privacy considerations dictate that the user have considerable
control over cookie management. The PRIVACY section contains more
information.

4.3.4 Sending Cookies to the Origin Server

When it sends a request to an origin server, the user agent sends a
Cookie request header to the origin server if it has cookies that are
applicable to the request, based on

* the request-host;

* the request-URI;

* the cookie's age.

The syntax for the header is:

cookie = "Cookie:" cookie-version
1*((";" | ",") cookie-value)
cookie-value = NAME "=" VALUE [";" path] [";" domain]
cookie-version = "$Version" "=" value
NAME = attr
VALUE = value
path = "$Path" "=" value
domain = "$Domain" "=" value

The value of the cookie-version attribute must be the value from the
Version attribute, if any, of the corresponding Set-Cookie response
header. Otherwise the value for cookie-version is 0. The value for
the path attribute must be the value from the Path attribute, if any,
of the corresponding Set-Cookie response header. Otherwise the
attribute should be omitted from the Cookie request header. The
value for the domain attribute must be the value from the Domain
attribute, if any, of the corresponding Set-Cookie response header.
Otherwise the attribute should be omitted from the Cookie request
header.

Note that there is no Comment attribute in the Cookie request header
corresponding to the one in the Set-Cookie response header. The user
agent does not return the comment information to the origin server.

The following rules apply to choosing applicable cookie-values from
among all the cookies the user agent has.

Domain Selection
The origin server's fully-qualified host name must domain-match
the Domain attribute of the cookie.

Path Selection
The Path attribute of the cookie must match a prefix of the
request-URI.

Max-Age Selection
Cookies that have expired should have been discarded and thus
are not forwarded to an origin server.

If multiple cookies satisfy the criteria above, they are ordered in
the Cookie header such that those with more specific Path attributes
precede those with less specific. Ordering with respect to other
attributes (e.g., Domain) is unspecified.

Note: For backward compatibility, the separator in the Cookie header
is semi-colon (;) everywhere. A server should also accept comma (,)
as the separator between cookie-values for future compatibility.

4.3.5 Sending Cookies in Unverifiable Transactions

Users must have control over sessions in order to ensure privacy.
(See PRIVACY section below.) To simplify implementation and to
prevent an additional layer of complexity where adequate safeguards
exist, however, this document distinguishes between transactions that
are verifiable and those that are unverifiable. A transaction is
verifiable if the user has the option to review the request-URI prior
to its use in the transaction. A transaction is unverifiable if the
user does not have that option. Unverifiable transactions typically
arise when a user agent automatically requests inlined or embedded
entities or when it resolves redirection (3xx) responses from an
origin server. Typically the origin transaction, the transaction
that the user initiates, is verifiable, and that transaction may
directly or indirectly induce the user agent to make unverifiable
transactions.

When it makes an unverifiable transaction, a user agent must enable a
session only if a cookie with a domain attribute D was sent or
received in its origin transaction, such that the host name in the
Request-URI of the unverifiable transaction domain-matches D.

This restriction prevents a malicious service author from using
unverifiable transactions to induce a user agent to start or continue
a session with a server in a different domain. The starting or
continuation of such sessions could be contrary to the privacy
expectations of the user, and could also be a security problem.

User agents may offer configurable options that allow the user agent,
or any autonomous programs that the user agent executes, to ignore
the above rule, so long as these override options default to "off".

Many current user agents already provide a review option that would
render many links verifiable. For instance, some user agents display
the URL that would be referenced for a particular link when the mouse
pointer is placed over that link. The user can therefore determine
whether to visit that site before causing the browser to do so.
(Though not implemented on current user agents, a similar technique
could be used for a button used to submit a form -- the user agent

could display the action to be taken if the user were to select that
button.) However, even this would not make all links verifiable; for
example, links to automatically loaded images would not normally be
subject to "mouse pointer" verification.

Many user agents also provide the option for a user to view the HTML
source of a document, or to save the source to an external file where
it can be viewed by another application. While such an option does
provide a crude review mechanism, some users might not consider it
acceptable for this purpose.

4.4 How an Origin Server Interprets the Cookie Header

A user agent returns much of the information in the Set-Cookie header
to the origin server when the Path attribute matches that of a new
request. When it receives a Cookie header, the origin server should
treat cookies with NAMEs whose prefix is $ specially, as an attribute
for the adjacent cookie. The value for such a NAME is to be
interpreted as applying to the lexically (left-to-right) most recent
cookie whose name does not have the $ prefix. If there is no
previous cookie, the value applies to the cookie mechanism as a
whole. For example, consider the cookie

Cookie: $Version="1"; Customer="WILE_E_COYOTE";
$Path="/acme"

$Version applies to the cookie mechanism as a whole (and gives the
version number for the cookie mechanism). $Path is an attribute
whose value (/acme) defines the Path attribute that was used when the
Customer cookie was defined in a Set-Cookie response header.

4.5 Caching Proxy Role

One reason for separating state information from both a URL and
document content is to facilitate the scaling that caching permits.
To support cookies, a caching proxy must obey these rules already in
the HTTP specification:

* Honor requests from the cache, if possible, based on cache validity
rules.

* Pass along a Cookie request header in any request that the proxy
must make of another server.

* Return the response to the client. Include any Set-Cookie response
header.

* Cache the received response subject to the control of the usual
headers, such as Expires, Cache-control: no-cache, and Cache-
control: private,

* Cache the Set-Cookie subject to the control of the usual header,
Cache-control: no-cache="set-cookie". (The Set-Cookie header
should usually not be cached.)

Proxies must not introduce Set-Cookie (Cookie) headers of their own
in proxy responses (requests).

5. EXAMPLES

5.1 Example 1

Most detail of request and response headers has been omitted. Assume
the user agent has no stored cookies.

1. User Agent -> Server

POST /acme/login HTTP/1.1
[form data]

User identifies self via a form.

2. Server -> User Agent

HTTP/1.1 200 OK
Set-Cookie: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"

Cookie reflects user's identity.

3. User Agent -> Server

POST /acme/pickitem HTTP/1.1
Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
[form data]

User selects an item for "shopping basket."

4. Server -> User Agent

HTTP/1.1 200 OK
Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";
Path="/acme"

Shopping basket contains an item.

5. User Agent -> Server

POST /acme/shipping HTTP/1.1
Cookie: $Version="1";
Customer="WILE_E_COYOTE"; $Path="/acme";
Part_Number="Rocket_Launcher_0001"; $Path="/acme"
[form data]

User selects shipping method from form.

6. Server -> User Agent

HTTP/1.1 200 OK
Set-Cookie: Shipping="FedEx"; Version="1"; Path="/acme"

New cookie reflects shipping method.

7. User Agent -> Server

POST /acme/process HTTP/1.1
Cookie: $Version="1";
Customer="WILE_E_COYOTE"; $Path="/acme";
Part_Number="Rocket_Launcher_0001"; $Path="/acme";
Shipping="FedEx"; $Path="/acme"
[form data]

User chooses to process order.

8. Server -> User Agent

HTTP/1.1 200 OK

Transaction is complete.

The user agent makes a series of requests on the origin server, after
each of which it receives a new cookie. All the cookies have the
same Path attribute and (default) domain. Because the request URLs
all have /acme as a prefix, and that matches the Path attribute, each
request contains all the cookies received so far.

5.2 Example 2

This example illustrates the effect of the Path attribute. All
detail of request and response headers has been omitted. Assume the
user agent has no stored cookies.

Imagine the user agent has received, in response to earlier requests,
the response headers

Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";
Path="/acme"

and

Set-Cookie: Part_Number="Riding_Rocket_0023"; Version="1";
Path="/acme/ammo"

A subsequent request by the user agent to the (same) server for URLs
of the form /acme/ammo/... would include the following request
header:

Cookie: $Version="1";
Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo";
Part_Number="Rocket_Launcher_0001"; $Path="/acme"

Note that the NAME=VALUE pair for the cookie with the more specific
Path attribute, /acme/ammo, comes before the one with the less
specific Path attribute, /acme. Further note that the same cookie
name appears more than once.

A subsequent request by the user agent to the (same) server for a URL
of the form /acme/parts/ would include the following request header:

Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001"; $Path="/acme"

Here, the second cookie's Path attribute /acme/ammo is not a prefix
of the request URL, /acme/parts/, so the cookie does not get
forwarded to the server.

6. IMPLEMENTATION CONSIDERATIONS

Here we speculate on likely or desirable details for an origin server
that implements state management.

6.1 Set-Cookie Content

An origin server's content should probably be divided into disjoint
application areas, some of which require the use of state
information. The application areas can be distinguished by their
request URLs. The Set-Cookie header can incorporate information
about the application areas by setting the Path attribute for each
one.

The session information can obviously be clear or encoded text that
describes state. However, if it grows too large, it can become
unwieldy. Therefore, an implementor might choose for the session
information to be a key to a server-side resource. Of course, using

a database creates some problems that this state management
specification was meant to avoid, namely:

1. keeping real state on the server side;

2. how and when to garbage-collect the database entry, in case the
user agent terminates the session by, for example, exiting.

6.2 Stateless Pages

Caching benefits the scalability of WWW. Therefore it is important
to reduce the number of documents that have state embedded in them
inherently. For example, if a shopping-basket-style application
always displays a user's current basket contents on each page, those
pages cannot be cached, because each user's basket's contents would
be different. On the other hand, if each page contains just a link
that allows the user to "Look at My Shopping Basket", the page can be
cached.

6.3 Implementation Limits

Practical user agent implementations have limits on the number and
size of cookies that they can store. In general, user agents' cookie
support should have no fixed limits. They should strive to store as
many frequently-used cookies as possible. Furthermore, general-use
user agents should provide each of the following minimum capabilities
individually, although not necessarily simultaneously:

* at least 300 cookies

* at least 4096 bytes per cookie (as measured by the size of the
characters that comprise the cookie non-terminal in the syntax
description of the Set-Cookie header)

* at least 20 cookies per unique host or domain name

User agents created for specific purposes or for limited-capacity
devices should provide at least 20 cookies of 4096 bytes, to ensure
that the user can interact with a session-based origin server.

The information in a Set-Cookie response header must be retained in
its entirety. If for some reason there is inadequate space to store
the cookie, it must be discarded, not truncated.

Applications should use as few and as small cookies as possible, and
they should cope gracefully with the loss of a cookie.

6.3.1 Denial of Service Attacks

User agents may choose to set an upper bound on the number of cookies
to be stored from a given host or domain name or on the size of the
cookie information. Otherwise a malicious server could attempt to
flood a user agent with many cookies, or large cookies, on successive
responses, which would force out cookies the user agent had received
from other servers. However, the minima specified above should still
be supported.

7. PRIVACY

7.1 User Agent Control

An origin server could create a Set-Cookie header to track the path
of a user through the server. Users may object to this behavior as
an intrusive accumulation of information, even if their identity is
not evident. (Identity might become evident if a user subsequently
fills out a form that contains identifying information.) This state
management specification therefore requires that a user agent give
the user control over such a possible intrusion, although the
interface through which the user is given this control is left
unspecified. However, the control mechanisms provided shall at least
allow the user

* to completely disable the sending and saving of cookies.

* to determine whether a stateful session is in progress.

* to control the saving of a cookie on the basis of the cookie's
Domain attribute.

Such control could be provided by, for example, mechanisms

* to notify the user when the user agent is about to send a cookie
to the origin server, offering the option not to begin a session.

* to display a visual indication that a stateful session is in
progress.

* to let the user decide which cookies, if any, should be saved
when the user concludes a window or user agent session.

* to let the user examine the contents of a cookie at any time.

A user agent usually begins execution with no remembered state
information. It should be possible to configure a user agent never
to send Cookie headers, in which case it can never sustain state with

an origin server. (The user agent would then behave like one that is
unaware of how to handle Set-Cookie response headers.)

When the user agent terminates execution, it should let the user
discard all state information. Alternatively, the user agent may ask
the user whether state information should be retained; the default
should be "no". If the user chooses to retain state information, it
would be restored the next time the user agent runs.

NOTE: User agents should probably be cautious about using files to
store cookies long-term. If a user runs more than one instance of
the user agent, the cookies could be commingled or otherwise messed
up.

7.2 Protocol Design

The restrictions on the value of the Domain attribute, and the rules
concerning unverifiable transactions, are meant to reduce the ways
that cookies can "leak" to the "wrong" site. The intent is to
restrict cookies to one, or a closely related set of hosts.
Therefore a request-host is limited as to what values it can set for
Domain. We consider it acceptable for hosts host1.foo.com and
host2.foo.com to share cookies, but not a.com and b.com.

Similarly, a server can only set a Path for cookies that are related
to the request-URI.

8. SECURITY CONSIDERATIONS

8.1 Clear Text

The information in the Set-Cookie and Cookie headers is unprotected.
Two consequences are:

1. Any sensitive information that is conveyed in them is exposed
to intruders.

2. A malicious intermediary could alter the headers as they travel
in either direction, with unpredictable results.

These facts imply that information of a personal and/or financial
nature should only be sent over a secure channel. For less sensitive
information, or when the content of the header is a database key, an
origin server should be vigilant to prevent a bad Cookie value from
causing failures.

8.2 Cookie Spoofing

Proper application design can avoid spoofing attacks from related
domains. Consider:

1. User agent makes request to victim.cracker.edu, gets back
cookie session_id="1234" and sets the default domain
victim.cracker.edu.

2. User agent makes request to spoof.cracker.edu, gets back
cookie session-id="1111", with Domain=".cracker.edu".

3. User agent makes request to victim.cracker.edu again, and
passes

Cookie: $Version="1";
session_id="1234";
session_id="1111"; $Domain=".cracker.edu"

The server at victim.cracker.edu should detect that the second
cookie was not one it originated by noticing that the Domain
attribute is not for itself and ignore it.

8.3 Unexpected Cookie Sharing

A user agent should make every attempt to prevent the sharing of
session information between hosts that are in different domains.
Embedded or inlined objects may cause particularly severe privacy
problems if they can be used to share cookies between disparate
hosts. For example, a malicious server could embed cookie
information for host a.com in a URI for a CGI on host b.com. User
agent implementors are strongly encouraged to prevent this sort of
exchange whenever possible.

9. OTHER, SIMILAR, PROPOSALS

Three other proposals have been made to accomplish similar goals.
This specification is an amalgam of Kristol's State-Info proposal and
Netscape's Cookie proposal.

Brian Behlendorf proposed a Session-ID header that would be user-
agent-initiated and could be used by an origin server to track
"clicktrails". It would not carry any origin-server-defined state,
however. Phillip Hallam-Baker has proposed another client-defined
session ID mechanism for similar purposes.

While both session IDs and cookies can provide a way to sustain
stateful sessions, their intended purpose is different, and,
consequently, the privacy requirements for them are different. A
user initiates session IDs to allow servers to track progress through
them, or to distinguish multiple users on a shared machine. Cookies
are server-initiated, so the cookie mechanism described here gives
users control over something that would otherwise take place without
the users' awareness. Furthermore, cookies convey rich, server-
selected information, whereas session IDs comprise user-selected,
simple information.

10. HISTORICAL

10.1 Compatibility With Netscape's Implementation

HTTP/1.0 clients and servers may use Set-Cookie and Cookie headers
that reflect Netscape's original cookie proposal. These notes cover
inter-operation between "old" and "new" cookies.

10.1.1 Extended Cookie Header

This proposal adds attribute-value pairs to the Cookie request header
in a compatible way. An "old" client that receives a "new" cookie
will ignore attributes it does not understand; it returns what it
does understand to the origin server. A "new" client always sends
cookies in the new form.

An "old" server that receives a "new" cookie will see what it thinks
are many cookies with names that begin with a $, and it will ignore
them. (The "old" server expects these cookies to be separated by
semi-colon, not comma.) A "new" server can detect cookies that have
passed through an "old" client, because they lack a $Version
attribute.

10.1.2 Expires and Max-Age

Netscape's original proposal defined an Expires header that took a
date value in a fixed-length variant format in place of Max-Age:

Wdy, DD-Mon-YY HH:MM:SS GMT

Note that the Expires date format contains embedded spaces, and that
"old" cookies did not have quotes around values. Clients that
implement to this specification should be aware of "old" cookies and
Expires.

10.1.3 Punctuation

In Netscape's original proposal, the values in attribute-value pairs
did not accept "-quoted strings. Origin servers should be cautious
about sending values that require quotes unless they know the
receiving user agent understands them (i.e., "new" cookies). A
("new") user agent should only use quotes around values in Cookie
headers when the cookie's version(s) is (are) all compliant with this
specification or later.

In Netscape's original proposal, no whitespace was permitted around
the = that separates attribute-value pairs. Therefore such
whitespace should be used with caution in new implementations.

10.2 Caching and HTTP/1.0

Some caches, such as those conforming to HTTP/1.0, will inevitably
cache the Set-Cookie header, because there was no mechanism to
suppress caching of headers prior to HTTP/1.1. This caching can lead
to security problems. Documents transmitted by an origin server
along with Set-Cookie headers will usually either be uncachable, or
will be "pre-expired". As long as caches obey instructions not to
cache documents (following Expires: <a date in the past> or Pragma:
no-cache (HTTP/1.0), or Cache-control: no-cache (HTTP/1.1))
uncachable documents present no problem. However, pre-expired
documents may be stored in caches. They require validation (a
conditional GET) on each new request, but some cache operators loosen
the rules for their caches, and sometimes serve expired documents
without first validating them. This combination of factors can lead
to cookies meant for one user later being sent to another user. The
Set-Cookie header is stored in the cache, and, although the document
is stale (expired), the cache returns the document in response to
later requests, including cached headers.

11. ACKNOWLEDGEMENTS

This document really represents the collective efforts of the
following people, in addition to the authors: Roy Fielding, Marc
Hedlund, Ted Hardie, Koen Holtman, Shel Kaphan, Rohit Khare.

12. AUTHORS' ADDRESSES

David M. Kristol
Bell Laboratories, Lucent Technologies
600 Mountain Ave. Room 2A-227
Murray Hill, NJ 07974

Phone: (908) 582-2250
Fax: (908) 582-5809
EMail: dmk@bell-labs.com

Lou Montulli
Netscape Communications Corp.
501 E. Middlefield Rd.
Mountain View, CA 94043

Phone: (415) 528-2600
EMail: montulli@netscape.com

Posted by 방글24

    Client Side State - HTTP Cookies



Original of this text is here(www.netscape.com/newsref/std/cookie_spec.html)

PERSISTENT CLIENT STATE
HTTP COOKIES

Preliminary Specification - Use with caution


    Introduction

Cookies are a general mechanism which server side connections (such as CGI scripts) can use to both store and retrieve information on the client side of the connection. The addition of a simple, persistent, client-side state significantly extends the capabilities of Web-based client/server applications.

    Overview

A server, when returning an HTTP object to a client, may also send a piece of state information which the client will store. Included in that state object is a description of the range of URLs for which that state is valid. Any future HTTP requests made by the client which fall in that range will include a transmittal of the current value of the state object from the client back to the server. The state object is called a cookie, for no compelling reason.

This simple mechanism provides a powerful new tool which enables a host of new types of applications to be written for web-based environments. Shopping applications can now store information about the currently selected items, for fee services can send back registration information and free the client from retyping a user-id on next connection, sites can store per-user preferences on the client, and have the client supply those preferences every time that site is connected to.

    Specification

A cookie is introduced to the client by including a Set-Cookie header as part of an HTTP response, typically this will be generated by a CGI script.

    Syntax of the Set-Cookie HTTP Response Header

This is the format a CGI script would use to add to the HTTP headers a new piece of data which is to be stored by the client for later retrieval.
Set-Cookie: NAME=VALUE; expires=DATE;
path=PATH; domain=DOMAIN_NAME; secure
NAME=VALUE
This string is a sequence of characters excluding semi-colon, comma and white space. If there is a need to place such data in the name or value, some encoding method such as URL style %XX encoding is recommended, though no encoding is defined or required.

This is the only required attribute on the Set-Cookie header.

expires=DATE
The expires attribute specifies a date string that defines the valid life time of that cookie. Once the expiration date has been reached, the cookie will no longer be stored or given out.

The date string is formatted as:

Wdy, DD-Mon-YYYY HH:MM:SS GMT
This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, with the variations that the only legal time zone is GMT and the separators between the elements of the date must be dashes.

expires is an optional attribute. If not specified, the cookie will expire when the user's session ends.

Note: There is a bug in Netscape Navigator version 1.1 and earlier. Only cookies whose path attribute is set explicitly to "/" will be properly saved between sessions if they have an expires attribute.

domain=DOMAIN_NAME
When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is made with the Internet domain name of the host from which the URL will be fetched. If there is a tail match, then the cookie will go through path matching to see if it should be sent. "Tail matching" means that domain attribute is matched against the tail of the fully qualified domain name of the host. A domain attribute of "acme.com" would match host names "anvil.acme.com" as well as "shipping.crate.acme.com".

Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT".

The default value of domain is the host name of the server which generated the cookie response.

path=PATH
The path attribute is used to specify the subset of URLs in a domain for which the cookie is valid. If a cookie has already passed domain matching, then the pathname component of the URL is compared with the path attribute, and if there is a match, the cookie is considered valid and is sent along with the URL request. The path "/foo" would match "/foobar" and "/foo/bar.html". The path "/" is the most general path.

If the path is not specified, it as assumed to be the same path as the document being described by the header which contains the cookie.

secure
If a cookie is marked secure, it will only be transmitted if the communications channel with the host is a secure one. Currently this means that secure cookies will only be sent to HTTPS (HTTP over SSL) servers.

If secure is not specified, a cookie is considered safe to be sent in the clear over unsecured channels.

    Syntax of the Cookie HTTP Request Header

When requesting a URL from an HTTP server, the browser will match the URL against all cookies and if any of them match, a line containing the name/value pairs of all matching cookies will be included in the HTTP request. Here is the format of that line:
Cookie: NAME1=OPAQUE_STRING1; NAME2=OPAQUE_STRING2 ...

    Additional Notes

  • Multiple Set-Cookie headers can be issued in a single server response.
  • Instances of the same path and name will overwrite each other, with the latest instance taking precedence. Instances of the same path but different names will add additional mappings.
  • Setting the path to a higher-level value does not override other more specific path mappings. If there are multiple matches for a given cookie name, but with separate paths, all the matching cookies will be sent. (See examples below.)
  • The expires header lets the client know when it is safe to purge the mapping but the client is not required to do so. A client may also delete a cookie before it's expiration date arrives if the number of cookies exceeds its internal limits.
  • When sending cookies to a server, all cookies with a more specific path mapping should be sent before cookies with less specific path mappings. For example, a cookie "name1=foo" with a path mapping of "/" should be sent after a cookie "name1=foo2" with a path mapping of "/bar" if they are both to be sent.
  • There are limitations on the number of cookies that a client can store at any one time. This is a specification of the minimum number of cookies that a client should be prepared to receive and store.
    • 300 total cookies
    • 4 kilobytes per cookie, where the name and the OPAQUE_STRING combine to form the 4 kilobyte limit.
    • 20 cookies per server or domain. (note that completely specified hosts and domains are treated as separate entities and have a 20 cookie limitation for each, not combined)
    Servers should not expect clients to be able to exceed these limits. When the 300 cookie limit or the 20 cookie per server limit is exceeded, clients should delete the least recently used cookie. When a cookie larger than 4 kilobytes is encountered the cookie should be trimmed to fit, but the name should remain intact as long as it is less than 4 kilobytes.
  • If a CGI script wishes to delete a cookie, it can do so by returning a cookie with the same name, and an expires time which is in the past. The path and name must match exactly in order for the expiring cookie to replace the valid cookie. This requirement makes it difficult for anyone but the originator of a cookie to delete a cookie.
  • When caching HTTP, as a proxy server might do, the Set-cookie response header should never be cached.
  • If a proxy server receives a response which contains a Set-cookie header, it should propagate the Set-cookie header to the client, regardless of whether the response was 304 (Not Modified) or 200 (OK).

    Similarly, if a client request contains a Cookie: header, it should be forwarded through a proxy, even if the conditional If-modified-since request is being made.

    Examples

Here are some sample exchanges which are designed to illustrate the use of cookies.

First Example transaction sequence:

Client requests a document, and receives in the response:
Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT
When client requests a URL in path "/" on this server, it sends:
Cookie: CUSTOMER=WILE_E_COYOTE
Client requests a document, and receives in the response:
Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
When client requests a URL in path "/" on this server, it sends:
Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
Client receives:
Set-Cookie: SHIPPING=FEDEX; path=/foo
When client requests a URL in path "/" on this server, it sends:
Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
When client requests a URL in path "/foo" on this server, it sends:
Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX

Second Example transaction sequence:

Assume all mappings from above have been cleared.
Client receives:
Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
When client requests a URL in path "/" on this server, it sends:
Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001
Client receives:
Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo
When client requests a URL in path "/ammo" on this server, it sends:
Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001
NOTE: There are two name/value pairs named "PART_NUMBER" due to the inheritance of the "/" mapping in addition to the "/ammo" mapping.

Corporate Sales: 415/937-2555; Personal Sales: 415/937-3777; Government Sales: 415/937-3678
If you have any questions, please visit Customer Service.

Copyright ⓒ 1997 Netscape Communications Corporation


Posted by 방글24
쿠키는 서버와 클라이언트 사이에 정보를 주고 받을 수 있는 통로인 동시에, 서버가 사용할 수 있는 유일한 로컬시스템(클라이언트) 자원입니다. 이러한 쿠키를 이용하면 방문자에게 좀 더 친밀한(?) 서비스를 제공할 수 있는 웹사이트를 구성할 수 있습니다.
하지만 쿠키가 로컬시스템에 저장된다는 것 때문에 혹시 나의 정보가 나도 모르게 외부로 유출되지 않는가 하는 걱정을 하게 만드는 것도 쿠키입니다.
여기서는 쿠키가 매우 유용한 도구라는 긍정적인 면에서 쿠키정보를 다루기 위한 클래스를 작성해 보려 합니다. 이 클래스는 세셔너에 포함된 세셔너핸들러 쿠키용과 비교해 볼 때 유사한 부분이 많이 있습니다. 그러나 쿠키만을 위해 제작되었기 때문에 소스 분석하기에는(이해하기에는) 훨씬 수월할 것입니다. 이 클래스는 쿠키를 요리하는 도구의 역할을 하기 때문에 이름을 쿠커(cooker)라고 정했습니다.
쿠키(cooker - class.cooker.php)를 이용하는 것이 보안상 여러가지 문제를 가지고 있음에도 불구하고 제가 쿠커를 작성하는 것은 쿠키가 세션과 같은 다른 방법보다는 이해하기가 쉽고 웹문서를 작성하기가 편하고 단순하다는 것입니다. 또한 서버자원이 아닌 방문자의 로컬시스템 하드디스크에 쿠키정보를 저장하게 되어 많은 방문자가 동시에 접속하는 웹사이트에서는 많은 장점을 가지게 됩니다. 그리고 보안에 조금만 주의를 기울인다면 아주 민감한 정보가 아닌 이상은 적용하는데 별 무리가 없다는 이유도 있습니다. 제 자신과 여러분에게도 한번쯤은 쿠키 사용법을 습득할 수 있는 기회가 될 수도 있겠지요.
쿠커란?
쿠키를 직접 관리해주는 클래스입니다. 클라이언트에서 날라온 쿠키값을 디코딩(암호 해독 과정 포함)하여 얻은 정보를 이용해 쿠키변수를 설정합니다. 이 과정에서 쿠키가 담고 있는 현재 상태를 얻을 수 있습니다. 새로운 쿠키를 생성할 때는 쿠키변수 정보를 인코딩(암호화 과정 포함)하여 이 정보를 클라이언트로 보내어 쿠키파일에 저장할 수 있도록 합니다. 인코딩 과정에서 쿠키변수 정보와 함께 클라이언트 IP 및 현재 시간을 함께 담아 보내게 되며 이러한 정보는 다음 페이지에서 쿠키를 디코딩하는 과정에서 추출되어 적절히 이용하게 됩니다. 클라이언트 IP는 보안을 고려할 때 필요한 정보이고 현재 시간은 쿠키의 유효기간을 결정하기 위한 정보로 사용됩니다.
< 쿠커의 역할 >
쿠키의 유효기간
쿠키의 유효기간은 우선 params() 메소드로 설정할 수 있습니다. params()에 의해 쿠키 생성할 때 설정된 유효기간은 웹브라우저에 의해 관리됩니다. params() 메소드에서 lifetime의 기본값은 0입니다. 따라서 브라우저가 살아있는 동안만 쿠키가 존재합니다. 브라우저를 종료하는 즉시 쿠키 정보도 같이 사라집니다.
서버에서 관리되는 쿠키의 유효기간이 별도로 존재합니다. 브라우저에서 관리되는 lifetime과 독립적으로 서버에서는 쿠키 생성 후 31536001초(1년)가 지나면 쿠커가 생성한 쿠키를 삭제하도록 되어있습니다. 이 값은 gc_maxlifetime() 메소드로 변경될 수 있습니다.
gc_maxlifetime() 함수로 유효기간을 설정하는 것은 쿠키를 처음 생성할 때 한번만 수행하면 됩니다. 따라서 여러페이지에 걸쳐 쿠커를 사용할 때는 처음 진입하는 페이지에서만 이 함수로 유효기간을 설정하면 됩니다. 다른 페이지에서는 이 함수를 사용하지 않더라도 이미 유효기간에 대한 정보가 쿠키 내에 포함되어 있으므로 자동으로 수행할 수 있습니다.
제공되는 메소드
메소드 버전 기능
start 0.0.1 쿠키파일로부터 쿠키정보를 전달받아 쿠키변수 설정
params 0.0.1 쿠키 설정 매개변수 획득/설정
gc_maxlifetime 0.0.2 서버상에서 확인하는 쿠키의 생존시간 획득/설정
name 0.0.1 쿠키파일에 저장될 쿠키명 획득/설정
get 0.0.1 쿠키변수값 획득
set 0.0.1 쿠키변수 등록 및 값 설정
isset2 0.0.2 쿠키변수 존재여부 확인
unset2 0.0.1 쿠키변수 삭제
write 0.0.1 쿠키변수에 기록된 쿠키정보를 쿠키파일에 저장
delete 0.0.1 쿠키변수 삭제, 쿠키파일의 쿠키삭제
메소드 사용법
int start(void)
클라이언트에서 전달된 쿠키를 받아 그 정보를 디코딩한 후 방문자 IP, 쿠키에 마지막으로 접근한 시간, 쿠키변수를 설정합니다. 그리고 쿠키와 PHP에 의해 자동으로 만들어지는 $HTTP_COOKIE_VARS["쿠키명"] 및 해당 전역변수를 삭제합니다. 따라서 이들 전역변수에 의해 쿠키값에 접근할 수 없습니다. 쿠키명은 디폴트로 "PHP_AUTH_DATA"로 지정되어 있습니다.
방문자 IP, 쿠키에 마지막으로 접근한 시간, 쿠키변수 정보를 통해 쿠키의 현재 상태를 파악해 그 값을 되돌려 줍니다. 마지막으로 현재 시간을 기준으로 쿠키파일의 쿠키를 업데이트합니다.
< start() 함수의 동작 >
반환되는 상태값을 보면 다음과 같습니다.
상태값 설명
0 등록된 쿠키변수가 존재함(정상적인 상태)
1 초기 상태(이전에 쿠키가 생성된 적이 없거나 브라우저가 쿠키를 받아들이지 않음)
2 쿠키가 만료되었음, 따라서 등록된 모든 쿠키변수가 삭제되었음
3 등록된 쿠키변수가 없음
4 앞서 쿠키를 생성한 방문자 IP와 현재 방문자 IP가 다름(이상한 사람임)
[code php;gutter:false] <?php

require "./cooker/class.cooker.php"; // 쿠키정보 클래스

$cooker = new Cooker;

$cooker->params(3600);
$status = $cooker->start();

switch ($status) {
case 0:
echo "이전 페이지에서 쿠키변수를 등록하셨군요.\n"";
echo "\n";
echo "USERID=".$cooker->get("USERID")."\n"";
echo "DATA=".$cooker->get("DATA")."\n"";
$cooker->delete();
echo "쿠키변수 및 쿠키파일의 쿠커정보를 지웠습니다.\n"";
echo "USERID=".$cooker->get("USERID")."\n"";
echo "DATA=".$cooker->get("DATA")."\n"";
break;
case 1:
$data = "처음으로 구원진 쿠키";
$cooker->set("USERID", "hwooky");
$cooker->set("DATA", $data);
$cooker->write();
echo "이전에 쿠키가 생성된 적이 없거나"
." 브라우저가 쿠키를 받아들이지 않습니다.\n"";
echo "\n";
echo "USERID=hwooky\n"";
echo "DATA=$data\n"";
echo "새로운 쿠키를 구웠습니다.\n"";
break;
case 2:
$data = "쿠키가 만료되었습니다.";
break;
case 3:
echo "등록된 쿠키변수가 없습니다.\n"";
break;
case 4:
echo "어떻게 들어오셨어요???\n"";
break;
}

echo "<A href=$PHP_SELF?id=$id>다시실행</A>";

?> [/code]
쿠커 내부에서 기본으로 설정된 유효기간은 24분(1440초)입니다. 이것은 세션함수에서의 유효기간 기본값과 같습니다.
void params(int lifetime [, string path [, string domain]])
PHP4 세션함수에서 session_set_cookie_params() 함수와 같이 쿠키를 생성할 때 필요한 유효기간, 유효경로, 유효도메인을 설정하는데 사용되는 함수입니다. 이 함수는 반드시 start() 함수보다 앞서 수행하여야 합니다. 각 매개변수에 대한 자세한 설명을 앞장("쿠키 규격") 및 PHP4 메뉴얼 세션함수를 참조바랍니다.
[code php;gutter:false] $cooker->params(3600, "/phpclass/exam/cooker/", ".phpclass.com"); [/code]
첫번째 매개변수 lifetime는 쿠키가 생존하는 시간을 초로 나타냅니다. 3600초라고 지정하면 쿠키를 생성한 후 1시간이 지나면 쿠키는 더 이상 유효하지 않습니다. 이 값의 디폴트 값은 0이며 이 경우의 쿠키는 사용자가 브라우저를 종료할 때까지만 존재합니다.
두번째 매개변수 path는 유효경로를 지정합니다. 특정 디렉토리에서만 이용할 필요가 있는 쿠키를 생성할 때 유효경로를 지정합니다. 위와 같이 "/phpclass/exam/cooker/"라고 지정하면 "http://www.phpclass.com/phpclass/exam/cooker/"의 디렉토리 및 그 하위디렉토리에 있는 웹문서만 사용할 수 있는 쿠키를 생성합니다. 다른 곳에 있는 웹문서는 이 쿠키를 받을 수 없습니다. 디폴트 값은 "/"이며 이 경우의 쿠키는 서버의 모든 디렉토리에서 유효합니다.
세번째 매개변수 domain은 쿠키의 유효도메인을 지정합니다. 위와 같이 ".phpclass.com"이라고 지정하면 www.phpclass.com, ftp.phpclass.com 등 도메인의 뒷부분이 일치하는 웹서버로만 쿠키가 전달됩니다. 디폴트 값은 ""이며 이 경우의 쿠키는 쿠키를 생성한 서버의 도메인으로 자동 지정됩니다.
array params()
PHP4 세션함수에서 session_get_cookie_params() 함수와 같은 역할을 수행합니다. 즉 쿠키를 생성할 때 필요한 유효기간, 유효경로, 유효도메인의 현재 설정값을 되돌려 줍니다.
[code php;gutter:false] $params = $cooker->params();
echo "유효기간=".$params["lifetime"]."\n""
echo "유효경로=".$params["path"]."\n""
echo "유효도메인=".$params["domain"]."\n"" [/code]
void gc_maxlifetime(int lifetime), int gc_maxlifetime(void)
위에 있는 params() 함수가 클라이언트에 생성하게 되는 쿠키의 유효기간을 설정하는 것이라면 gc_maxlifetime() 함수는 서버에서 쿠키의 유효기간을 확인할 수 있도록 그 시간을 설정하거나 획득하기 위한 함수입니다.
[code php;gutter:false] $cooker = new Cooker;
$cooker->params(0); //클라이언트에서의 쿠키지속시간
$cooker->gc_maxlifetime(1440); //서버에서의 쿠키지속시간(초단위/24분)
$cooker->start(); [/code]
위와 같은 경우 params()에서 lifetime을 0으로 설정하였기 때문에 클라이언트에서의 쿠키지속시간은 브라우저가 살아있는 한 계속 쿠키는 존재합니다. 그러나 쿠키가 생성된 후 24분이 지나면 서버에서 gc_maxlifetime(1440)에 의해 쿠키정보를 임의로 삭제하게 됩니다. 이러한 기능은 시간에 의한 자동로그아웃을 구현할 때 유용하게 사용될 수 있을 것입니다.
params()와 gc_maxlifetime() 함수에서 설정할 때는 모두 start() 함수 전에 수행하여야 합니다.
string name([string newname])
쿠커에서 사용되는 쿠키명(cookie name)을 얻거나 새로운 쿠키명으로 설정할 때 사용할 수 있습니다. 새로운 쿠키명을 설정할 때는 반드시 start() 함수보다 앞서 수행하여야 합니다. 쿠커는 기본적으로 쿠키명을 "PHP_AUTH_DATA"로 설정되어 있습니다. 보안을 위해 주기적으로 변경해주는 것이 바람직합니다.
[code php;gutter:false] $cooker = new Cooker;
$cooker->name("NEW_COOKIE_NAME");
$cooker->start();
.
.
. [/code]
array get(void)
등록된 모든 쿠키변수에 대한 정보를 되돌려줍니다. 정확한 정보를 얻기 위해서는 start() 함수를 먼저 수행하여야 합니다.
[code php;gutter:false] $list = $cooker->get();
if (is_array($list))
while(list($name,$value)=each($list))
echo "\$list[$name]=$value\n""; [/code]
string get(string name)
쿠키변수명을 입력 매개변수로 지정하면 해당 쿠키변수명에 대한 값을 되돌려 줍니다.
[code php;gutter:false] $userid = $cooker->get("USERID"); [/code]
void set(string name [, string value])
쿠키변수를 등록시켜주며 동시에 그 값을 설정합니다. 값을 지정하지 않으면 널문자열로 초기화합니다.
[code php;gutter:false] $cooker->set("USERID", "hwooky"); [/code]
bool isset2(string name)
등록된 쿠키변수가 존재하는지 확인합니다. 존재하면 true, 아니면 false를 반환합니다. 쿠키변수의 값이 null이더라도 존재한다면 true를 반환합니다.
[code php;gutter:false] if ($cooker->isset2("USERID"))
echo "쿠키변수 USERID가 존재하네요.\n""; [/code]
void unset2([string name])
등록된 쿠키변수를 삭제합니다. 입력 매개변수를 지정하지 않으면 모든 쿠키변수를 삭제합니다.
[code php;gutter:false] $cooker->unset2("USERID"); [/code]
쿠키변수를 삭제해 주는 함수의 함수명은 unset2입니다. 메소드명을 unset으로하여 함수를 정의하면 에러(Parse error)가 발생하여 할 수 없이 unset2로 명명하였습니다. 클래스 내에서 정의된 메소드명이라 내장함수 unset와 전혀 관련이 없는데도 에러가 나는 것을 보면 PHP의 버그가 아니면 unset() 함수가 다른 함수와 달리 PHP 내에서 특수하게 처리되는 것 같습니다. 이와같이 메소드명으로 사용할 수 없는 함수명으로는 unset 외에도 empty, isset 입니다. 모두 변수 처리 관련 함수들입니다.
void write(void)
등록된 쿠키변수와 기타 쿠키파일에 저장할 정보를 인코딩(암호화 포함)하여 쿠키파일에 저장합니다. start() 함수를 먼저 수행하여야 하며, 또한 내부적으로 PHP header() 함수를 사용하기 때문에 브라우저로 출력하는 문자가 발생하기 전에 수행하여야 합니다.
[code php;gutter:false] $cooker->write(); [/code]
void delete()
쿠키변수를 모두 삭제한 후 쿠키파일에서 쿠커가 사용하는 쿠키를 삭제합니다. write() 함수와는 달리 응답헤더 정보와 관계없이 수행합니다. 왜냐하면 쿠키를 삭제하기 위해 PHP header() 함수를 사용하지 않으며 자바스크립트의 document.cookie 객체를 이용합니다. 로그아웃과 같은 기능을 수행할 때 요긴하게 사용될 수 있을 것입니다. 없어도 로그아웃할 수는 있겠지만 보다 편하게 하기 위해 작성되었습니다.
[code php;gutter:false] $cookie->delete(); [/code]
데이터 암호화 클래스(class.crypto.php)
보안에 취약한 쿠키의 단점을 다소나마 보완하기 위해 쿠키값을 암호화하는데 활용할 수 있는 클래스입니다. 이 클래스는 제가 작성한 것이 아니며 hansanderson 라는 분이 작성하여 공개한 것을 포함시켰을 뿐입니다. 쿠키를 아무리 암호화한다고 해도 그 알고리즘이 노출된다면 본래의 목적이 반감될 수 밖에 없다는 것을 인식하시고 이 부분은 직접 작성할 것을 고려해 보시는 것이 좋을 듯합니다. 따라서 이 클래스는 참고용으로 첨부되어 있을 뿐입니다. 이 클래스에서 정의된 메소드는 쿠커(class.cooker.php)에서 사용하게 됩니다. 그러나 실제로 쿠커 내용을 보면 아시겠지만 데이터 암호화 클래스에 있는 메소드를 전혀 이용하지 않고 있습니다. 동일한 메소드를 쿠커 내에서 더미함수로 정의하여 사용하고 있습니다. 따라서 현재의 쿠커를 이용하더라도 쿠키의 암호화는 수행되지 않습니다. 이것은 여러분의 몪으로 남겨 놓겠습니다. 아래는 데이터 암호화 클래스(class.crypto.php)를 공개한 분에 대한 개인신상입니다.
AUTHOR hansanderson
HOME www.hansanderson.com/php/crypto/
EMAIL corporation@hansanderson.com
쿠커를 이용한 실험 예제
메뉴 "회원인증정보 >> 장바구니 클래스"에 있는 예제를 실험 대상으로 하였습니다. 자세한 것은 "장바구니 클래스"를 참조바랍니다.

Posted by 방글24