search
HomeBackend DevelopmentPHP Tutorial变量的“追随”:cookie与session_PHP

Cookie

变量的“追随”:cookie与session 作者:    来源: 互联网     浏览数:44

放大阅读

     字号选择:〖大 中 小〗

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

一.Cookie的使用

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

1. 设置一个Cookie变量

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

<code>int setcookie(string name, string value, int expire,
            string path, string domain, int secure);</code>

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

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

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

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

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

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

2. 销毁一个变量

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

<code>setcookie (“username” ,“”);</code>

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

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后也开始支持它了。首先,让我们来看看一个简单的例子:

<code>
            test.php
            -----------
            
            session_start();
            session_register(var); //注册变量var
            $var="这是SESSION变量的值"; //var变量已经被作为session变量
            ?>
            test1.php
            ------
            
            session_start();
            session_register(var);
            echo $var; //输出:“这是SESSION变量的值”
            ?>
            </code>
            

1、初始一个session

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

<code>: boolean session_start(void);</code>

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

2、在session中注册一个变量

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

<code>boolean session_register(string name);</code>

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

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

3、使用session变量的值

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

4、session的销毁

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

<code>boolean session_unregister(string name);</code>

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

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

<code>boolean session_destroy(void);</code>

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

5、其它有用的session函数

a、 检查变量是否注册

<code>boolean session_is_registered(string name);</code>

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

b、 给注册变量归null

<code> void session_unset(void); </code>

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

<code>
            <?php 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|
            </code>

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

<code>
            void session_set_save_handler (string open, string close, string read,
            string write, string destroy, string gc)
            </code>

  这个函数可以定义用户级的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方法。如果你想用数据库来实现,这也是很容易做到的。

<code>
            Example:session_set_save_handler() example
            <?php 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了。
            ?>
            </code>

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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor