2009년 10월 9일 금요일

[PHP] PHP SetCookie 사용법 (쿠키 Cookie)



Examples

Some examples follow how to send cookies:

Example #1 setcookie()>$2 send example

<?php
$value
= 'something from somewhere'
;

setcookie("TestCookie", $value
);
setcookie("TestCookie", $value, time()+3600);  
/* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1
);
?>

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5. To see the contents of our test cookie in a script, simply use one of the following examples:

<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"
];
echo
$HTTP_COOKIE_VARS["TestCookie"
];

// Another way to debug/test is to view all cookies
print_r($_COOKIE
);
?>

Example #2 setcookie()>$2 delete example

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:

<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600
);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".example.com", 1
);
?>

Example #3 setcookie()>$2 and arrays

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

<?php
// set the cookies
setcookie("cookie[three]", "cookiethree"
);
setcookie("cookie[two]", "cookietwo"
);
setcookie("cookie[one]", "cookieone"
);

// after the page reloads, print them out
if (isset($_COOKIE['cookie'
])) {
    foreach (
$_COOKIE['cookie'] as $name => $value
) {
        echo
"$name : $value <br />\n"
;
    }
}
?>

The above example will output:

three : cookiethree
two : cookietwo
one : cookieone

댓글 없음:

댓글 쓰기