Home  >  Article  >  Backend Development  >  php基础教程——3cookie跟session

php基础教程——3cookie跟session

WBOY
WBOYOriginal
2016-06-13 12:13:39878browse

php基础教程——3cookie和session

一、cookie

1.创建cookie,注:必须在发送其他任何信心之前从服务器发送到客户端,否则导致错误。

   使用函数发送cookie: setcookie(name, value);

2.读取cookie

    eg:setcookie('user', 'trout');

     $COOKIE['user'];

3.添加参数

   set(name, value, expiration, path, domain, sesure, httponly);

    参数简介:

     name键, value值,

     expiration存在时间,

     path和 domain限制在特定文件夹或域中才存在,

     sesure值1表必须使用安全连接,反之值0表不必要,

     httponly限制对cookie的访问,比如禁止Javascript对cookie的访问。

4.删除cookie

   使用通首次设置cookie时相同的参数,不设置值。

   eg:setcookie('user', 'larry');

   删除:setcookie('user', '');

编码测试:ws.php:

<?php if (isset($_POST[&#39;submitted&#39;])){	setcookie(&#39;font-size&#39;, $_POST[&#39;font_size&#39;], time() + 1000000000, &#39;/&#39;, &#39;&#39;, 0);	setcookie(&#39;font-color&#39;, $_POST[&#39;font_color&#39;], time() + 1000000000, &#39;/&#39;, &#39;&#39;, 0);	$msg = &#39;<p>setted!';}?>   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title><base>   <?phpif (isset($msg)){	print $msg;}?><p>Choose your preferences:</p>
<div><p>This is the foot of the document</p></div>  


二、session

1.session与cookie区别:

    1>session将信息保存于服务器,cookie保存于客户端

    2>session保存信息量更大

    3>session更安全

2.创建session,注:必须在向web发信息之前调用

   1>调用函数:session_start();

   2>通过数组$_SESSION进行数值记录:$_SESSION[' email '];

3.访问session:

   $_SESSION[' email '];

4.删除session:session数据存在两个地方,故从两个地方删除:

   1>session_start()

   2>unset($_SESSION);

   3>session_destory(); //删除服务器上的

编码测试:ws.php:

   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title><base>   <?phpdefine (&#39;TITLE&#39;, &#39;Login&#39;);if (isset($_POST[&#39;submitted&#39;])) {	if ((!empty($_POST[&#39;name&#39;])) && (!empty($_POST[&#39;password&#39;]))){		if ((strtolower($_POST[&#39;name&#39;]) == &#39;yf&#39;) && ($_POST[&#39;password&#39;] == &#39;123456&#39;)){// name and password are correct.			session_start();			$SESSION[&#39;name&#39;] = $_POST[&#39;name&#39;];			$SESSION[&#39;time&#39;] = time();						print &#39;<h1>The session content:' .$SESSION['name']."\n".$SESSION['time'].'';						unset($_SESSION);			session_destroy();			print 'destroy()!';		}		else {			print '<p> name or password is worry!</p>';		}	}	else {		print '<p> make sure you enter both name and password!</p>';	}}else {	print 		'

Name:

Password:

'; }?><div><p>This is the foot of the document</p></div>

测试裁图:



结果:


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn