cookie 常用于识别用户,cookie 是服务器留在用户计算机中的小文件,每当相同的计算机通过浏览器请求页面时,它同时会发送 cookie,通过 php,您能够创建并取回 cookie 的值.
如何创建 cookie?
setcookie() 函数用于设置 cookie.
注释:setcookie() 函数必须位于 <html> 标签之前.
语法:setcookie(name,value,expire,path,domain);例子.
在下面的例子中,我们将创建名为 "user" 的 cookie,把为它赋值 "alex porter",我们也规定了此 cookie 在一小时后过期.
最简单的cookie创建方法:
- <?php
- echo( "cookie created? : " . setcookie("cookie_name", "cookie_data" ) );
- ?>
实例二:cookies存数组
- <?
- setcookie("php[uid]", "1111111111111111", time()+3600);
- setcookie("php[color]", "black", time()+3600);
- setcookie("php[preference]", "english", time()+3600);
-
- if (isset ($php)) {
- while (list ($name, $value) = each ($php)) {
- echo "$name = $value<br>n";
- }
- }
- ?>
cookie删除:
- <?php
- setcookie ( "cookie_user", "test", time () + 60 * 60 * 24 * 30 );
- setcookie ( "cookie_pass", md5 ( "test" ), time () + 60 * 60 * 24 * 30 );
-
- function logout() {
- setcookie ( "cookie_user", "", time () + 60 * 60 * 24 * 30 );
- setcookie ( "cookie_pass", "", time () + 60 * 60 * 24 * 30 );
- }
- logout ();
- echo $_cookie ['cookie_user'] . "<br />";
- echo "you have successfully logged out.";
- ?>
下面一个利用cookies记录用户名自动登录函数实例:
- <?php
- $globals['username'] = "test";
- $globals['password'] = "test";
-
- function validatelogin ($username, $password){
- if (strcmp ($username, $globals['username']) == 0 && strcmp ($password, $globals['password']) == 0){
- setcookie ("cookie_user", $username, time()+60*60*24*30);
- setcookie ("cookie_pass", md5 ($password), time()+60*60*24*30);
- return true;
- } else {
- return false;
- }
- }
- if (validatelogin ("test","test")){
- echo "successfully logged in.";
- } else {
- echo "sorry, invalid login.";
- }
- ?>
(责任编辑:admin) |