Home php教程 php手册 变量的“追随”:cookie与session

变量的“追随”:cookie与session

Jun 21, 2016 am 09:10 AM
cookie quot session string

cookie|session|变量

在很多时候,我们需要跟踪浏览者在整个网站的活动,对他们身份进行自动或半自动的识别(也就是平时常说的网站登陆之类的功能),这时候,我们常采用一组变量来“追随”访客。实现变量“追随”有很多种方法,比较用得多的是cookie和session。下面我们用时下很流行的PHP为大家讲解一下它们的使用。

一.Cookie的使用

  Cookie是网站保存在浏览器客户端的信息,也就是说保存在访客的机器里的变量,一般随着HTTP头发送到客户端。在Cookie生效之后及失效之前,客户每次发出页面请求的时候,都会把Cookie一块发送到服务器,只要我们针对它进行相应的处理,就可以实现变量“追随”。

1. 设置一个Cookie变量

  设置一个Cookie变量,PHP使用的函数是:

int setcookie(string name, string value, int expire,
string path, string domain, int secure);


  其中name是Cookie变量名称标识,你在PHP中将可以象使用普通变量名一样来用它引用Cookie变量。value是Cookie变量的初始值,expire 表示该Cookie变量的有效时间;path 为该Cookie变量的相关路径;domain 表示Cookie变量的网站;secure 则需在 https 的安全传输时才有效。

  例如我们要设置一个变量username,它的值是字符串“bluewind”,我们可以这么写代码:

setcookie (“username”,“bluewind”); //这两个参数是setcookie必要的。


  我们还想给这个变量设置有效时间来限制操作超时等,比如说10分钟:

setcookie (“username”,“bluewind”, 600000); //有效时间的单位是毫秒。


  注意:setcookie和header函数一样,需要放在任何能向客户端输出的语句之前。

2. 销毁一个变量

  销毁Cookie变量只要将它的value设为空(“”)就可以了,如想销毁上面那个变量只要再写一次:

setcookie (“username” ,“”);


  就可以了。这常用作安全退出之用。

3. Cookie的有效范围和生存期

  Cookie的有效范围(也就是说在这个范围的页面都能得到这个Cookie变量)默认的是该目录及其子目录,当然你可以用setcookie的path和domain参数进行修改。如果你不对cookie的expire进行设置(参见1. 设置一个Cookie变量中的例子),那么当你离开网站的页面,cookie也同时得到自动销毁。

  http://www.netscape.com/newsref/std/cookie_spec.html是 cookie 原创者 Netscape 所提供的完整介绍信息。

二,session的使用

  session变量,也就是会话级变量,是访客在整个和网站交互的过程中都存在的公有变量。在客户端不支持有可能不支持cookie的时候(比如linux下的lynx……呵呵,惨了点),我们为了保证数据正确安全,就需要采用session变量。Session在各种网页语言中的实现方式不一样,PHP在4.0后也开始支持它了。首先,让我们来看看一个简单的例子:


test.php
-----------

session_start();
session_register(var); //注册变量var
$var="这是SESSION变量的值"; //var变量已经被作为session变量
?>
test1.php
------

session_start();
session_register(var);
echo $var; //输出:“这是SESSION变量的值”
?>



1、初始一个session

  如果PHP的设置自动session并没有开启的话,需要使用session_start()函数来初始化一个session,这个函数的用法如下:

: boolean session_start(void);


  它的作用是初始化一个新的 Session,若该客户已在 Session 之中,则连上原 Session。本函数没有参数,且返回值均为 true。

2、在session中注册一个变量

  你要在session保存的变量都必须使用下列函数对变量进行注册:

boolean session_register(string name);


  本函数在全局变量中增加一个变量到目前的 Session 之中。参数 name 即为欲加入的变量名。成功则返回true 值。

  然后你就可以直接使用变量名对它进行赋值,这个值就会被保存下来。

3、使用session变量的值

  如上例所示,只要你再在新的页面重复上两个步骤(除了赋值外),就可以直接使用session变量。

4、session的销毁

  如果你只是想注销一个变量而不是摧毁整个变量的话,那需要使用函数:

boolean session_unregister(string name);


  用法很简单,参数 name 即为欲删除的变量名。成功则返回 true 值。

  但是,如果要整个“摧毁”session变量的话,比如说安全退出什么的,使用函数:

boolean session_destroy(void);


  本函数结束目前的 Session。本函数没有参数,且返回值均为 true。

5、其它有用的session函数

a、 检查变量是否注册

boolean session_is_registered(string name);


  本函数可检查目前的 Session 之中是否已有指定的变量注册。参数 name 即为欲检查的变量名。成功则返回true 值。

b、 给注册变量归null

void session_unset(void);


  这个函数可以把当然注册的所有的session变量置为空。注意它不是unregister,也不同于destroy。 下面这个例子,对此函数做了很好的说明。


session_register('a','b','c'); //auto-session-start
$a=1;
$b=2;
$c=3;
session_unregister('a'); //unregistrered $a
echo "A: $a - reg:".session_is_registered('a')." ";
// but the global $a remains
session_unset(); // unsets $b und $c
echo "B:$b - reg:".session_is_registered('b')." ";
// the registration remains !
echo "C:$c - reg:".session_is_registered('c')." ";
echo session_encode();
?>

输出:
A: 1 - reg:
B: - reg:1
C: - reg:1
!b|!c|



c、定制你自己的session处理方法


void session_set_save_handler (string open, string close, string read,
string write, string destroy, string gc)



  这个函数可以定义用户级的session的保存函数(打开、关闭、写入等)。比如,我们想把session保存在本地的一个数据库中时,本函数就很有用了。缺省情况下,每个session存贮在系统临时目录的一个个独立文件中(例如在unix系统中为/tmp)。这适合或不适合,依你的需求而言。例如:如果你的支持php的web服务器分布在不同的机器上,你不能很容易地共享它们之间的session(当然,你也可以将sessions保存在NFS共享中)。另一个潜在的问题是你机器上的数千或数百万个session文件使你的文件系统变得散乱 。注意:这个函数是在4.0b4版本后才出现的。使用本函数前,先要配置php.ini文件,session.save_hadler=user ,否则,session_set_save_handler()不会生效。

  此外,根据我的测试,你如果想让这样的session跨页面使用,还要在每一个用到session的脚本文件中加入你自定的函数及session_set_save_handler,所以,最好的方法是做成一个单独的文件,在每一个要用到session的脚本中用include来包含进来。

  下面这个例子提供了一个最基本的session保存法,类似于默认的files方法。如果你想用数据库来实现,这也是很容易做到的。


Example:session_set_save_handler() example
function open ($save_path, $session_name) {
global $sess_save_path, $sess_session_name;
$sess_save_path = $save_path;
$sess_session_name = $session_name;
return(true);
}
function close() {
return(true);
}
function read ($id) {
global $sess_save_path, $sess_session_name;
$sess_file = "$sess_save_path/sess_$id";
if ($fp = @fopen($sess_file, "r")) {
$sess_data = fread($fp, filesize($sess_file));
return($sess_data);
} else {
return("");
}

}

function write ($id, $sess_data) {
global $sess_save_path, $sess_session_name;
$sess_file = "$sess_save_path/sess_$id";
if ($fp = @fopen($sess_file, "w")) {
return(fwrite($fp, $sess_data));
} else {
return(false);
}
}
function destroy ($id) {
global $sess_save_path, $sess_session_name;
$sess_file = "$sess_save_path/sess_$id";
return(@unlink($sess_file));
}

/*********************************************
* WARNING - You will need to implement some *
* * sort of garbage collection routine here. *
* *********************************************/
function gc ($maxlifetime) {
return true;
}
session_set_save_handler
("open", "close", "read", "write", "destroy", "gc");
session_start();
// proceed to use sessions normally
// 现在你就可以象往常一样地使用session了。

?>




Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

Does clearing cookies have any impact? Does clearing cookies have any impact? Sep 20, 2023 pm 06:01 PM

The effects of clearing cookies include resetting personalization settings and preferences, affecting ad experience, and destroying login status and password remembering functions. Detailed introduction: 1. Reset personalized settings and preferences. If cookies are cleared, the shopping cart will be reset to empty and products need to be re-added. Clearing cookies will also cause the login status on social media platforms to be lost, requiring re-adding. Enter your username and password; 2. It affects the advertising experience. If cookies are cleared, the website will not be able to understand our interests and preferences, and will display irrelevant ads, etc.

Frequently Asked Questions and Solutions about Cookie Settings Frequently Asked Questions and Solutions about Cookie Settings Jan 19, 2024 am 09:08 AM

Common problems and solutions for cookie settings, specific code examples are required. With the development of the Internet, cookies, as one of the most common conventional technologies, have been widely used in websites and applications. Cookie, simply put, is a data file stored on the user's computer that can be used to store the user's information on the website, including login name, shopping cart contents, website preferences, etc. Cookies are an essential tool for developers, but at the same time, cookie settings are often encountered

See all articles