PHP 新手入门之cookie 登录

PHP 新手入门之cookie

1.什么是cookie    它有什么样的作用

cookie 是一种服务器留在用户计算机上的小文件。每当同一台计算机通过浏览器请求页面时,这台计算机将会发送 cookie。通过 PHP,您能够创建并取回 cookie 的值

作用:通常用于识别用户

2.如何创建cookie

setcookie() 函数用于设置 cookie

注意:setcookie() 函数必须位于 <html> 标签之前

语法:setcookie(name, value, expire, path, domain);

<?php
	setcookie("user", "admin", time()+3600);
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>cookie</title>
</head>
<body>
	
</body>
</html>

注:如上案例所示 创建一个名为user  值为admin    同时也规定了,值在一个小时后消失

通过另外一种方式让cookie过期  如下代码所示

<?php
	$time = time() + 60*60*3600;
	setcookie("user", "admin",$time);
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>cookie</title>
</head>
<body>

</body>
</html>

如何取出cookie的值

<?php
	setcookie("user", "admin", time()+3600);
?>

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>cookie</title>
</head>
<body>
	<?php
		echo $_COOKIE['user'];
	?>
</body>
</html>

注意:当我们在开头写上了一个user 值为admin  要去运行一下这段代码,浏览器没有刷新,值是没有存入cookie的

运行完之后,在刷新一次页面就可以输出cookie中user的值了

4.如何删除cookie

当删除 cookie 时,您应当使过期日期变更为过去的时间点

<?php

// 设置 cookie 过期时间为过去 1 小时

setcookie("user", "", time()-3600);

?>

一般cookie 正常是用于表单提交的时候,把表单内的数据存入cookie 

下一节
<?php setcookie("user", "admin", time()+3600); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>cookie</title> </head> <body> </body> </html>
提交 重置代码
章节 评论 笔记 课件
  • 取消 回复 发送
  • 取消 发布笔记 发送