Home php教程 PHP源码 PHP中会话管理Cookie和Session的例子

PHP中会话管理Cookie和Session的例子

Jun 08, 2016 pm 05:20 PM
cookie nbsp quot session

PHP中会话管理包括了我们常用的session与cookie了,它们分别是在服务器端与客户端的两个会话了,下面一起来了解一下它们。

<script>ec(2);</script>

 

会话管理是web开发的一项重要内容,包括Session和Cookie两种技术。本章介绍Cookie和Session的创建和使用。

Cookie:

cookie 常用于识别用户。cookie 是服务器留在用户计算机中的小文件。每当相同的计算机通过浏览器请求页面时,它同时会发送 cookie。通过 PHP能够创建并取回 cookie 的值。cookie 只能读取所在域,单一域不能超过20个cookie,每个cookie文件长度上限位4k字节,浏览器最多储存300个cookie。

cookie的创建:

setcookie() 函数用于设置 cookie。注意:setcookie() 函数必须位于标签之前。

语法:

/**
* name:必需。规定 cookie 的名称。
* value:必需。规定 cookie 的值。
* expire:可选。规定 cookie 的有效期。
* path:可选。规定 cookie 的服务器路径。
* domain:可选。规定 cookie 的域名。
* secure:可选。规定是否通过安全的 HTTPS 连接来传输 cookie。
*/
setcookie(name,value,expire,path,domain,secure)
注释:在发送cookie时,cookie的值会自动进行URL编码。接收时会进行URL解码。

例子:

1.设置并发送 cookie:

$value = "my cookie value";
 
// 发送一个简单的 cookie
//cookie24小时过期
setcookie("TestCookie", $value, time()+3600*24);
?>
 

...
...
2.检索出 cookie 值的不同方法:




 
 
// 输出个别的 cookie
echo $_COOKIE["TestCookie"];
echo "
";
echo $HTTP_COOKIE_VARS["TestCookie"];
echo "
";
 
// 输出所有 cookie
print_r($_COOKIE);
?>
 

3.输出

my cookie value
my cookie value
Array ([TestCookie] => my cookie value)

4.删除 cookie

通过把失效日期设置为过去的日期/时间,删除一个 cookie:


// set the expiration date to one hour ago
setcookie("TestCookie", "", time()-3600);
?>

Session:

PHP session 变量用于存储有关用户会话的信息,或更改用户会话的设置。Session 变量保存的信息是单一用户的,并且可供应用程序中的所有页面使用。Session 的工作机制是:为每个访问者创建一个唯一的 id (UID),并基于这个 UID 来存储变量。UID 存储在 cookie 中,亦或通过 URL 进行传导。

session的创建:

在您把用户信息存储到 PHP session 中之前,首先必须启动会话。session_start() 函数必须位于标签之前。

语法:

session_start();

例子:

1.开始session


 


 

2.存储 session 变量

存储和取回 session 变量的正确方法是使用 $_SESSION 变量:


session_start();
// store session data
$_SESSION['views']=1;
?>
 


 
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
 

3.输出

Pageviews=1

4.终结 session
如果您希望删除某些 session 数据,可以使用 unset() 或 session_destroy() 函数。
unset() 函数用于释放指定的 session 变量:

unset($_SESSION['views']);
?>

您也可以通过 session_destroy() 函数彻底终结 session:


session_destroy();
?>

通过session设置用户登录后的显示信息

在网站的顶部通常会有用户登录和注册的入口,还有在用户登录之后,要显示出用户的信息,如帐号,还有将登录入口变为退出;

在使用symphony模板中,可以使用如下代码:

您好{{ app.session.get('member_name') }},欢迎来到**网!
 
{% if app.session.get('member_name') == null %}

  • 登录

  • 注册

  • {% elseif app.session.get('member_name') != "" %}
     
  • 退出

  •  
    {% endif %}
    一开始使用{% if app.session.get(‘member_name’) ==“”%}

    后来总报错,之后将改成null,即可以判断成功是否有用户的登录session。

     

    PHP中SESSION与COOKIE的区别

     这两者,区别和联系其实也挺深奥的,总是了解一些皮毛,每次都得上网查,今天写下来,每隔段时间就看看,加深记忆。
        Session是由应用服务器维持的一个服务器端的存储空间,用户在连接服务器时,会由服务器生成一个唯一的SessionID,用该SessionID 为标识符来存取服务器端的Session存储空间。而SessionID这一数据则是保存到客户端,用Cookie保存的,用户提交页面时,会将这一 SessionID提交到服务器端,来存取Session数据。这一过程,是不用开发人员干预的。所以一旦客户端禁用Cookie,那么Session也会失效。

        服务器也可以通过URL重写的方式来传递SessionID的值,因此不是完全依赖Cookie。如果客户端Cookie禁用,则服务器可以自动通过重写URL的方式来保存Session的值,并且这个过程对程序员透明。

        可以试一下,即使不写Cookie,在使用request.getCookies();取出的Cookie数组的长度也是1,而这个Cookie的名字就是JSESSIONID,还有一个很长的二进制的字符串,是SessionID的值。

        大家都知道,http是无状态的协议,客户每次读取web页面时,服务器都打开新的会话,而且服务器也不会自动维护客户的上下文信息,那么要怎么才能实现网上商店中的购物车呢,session就是一种保存上下文信息的机制,它是针对每一个用户的,变量的值保存在服务器端,通过SessionID来区分不同的客户,session是以cookie或URL重写为基础的,默认使用cookie来实现,系统会创造一个名为JSESSIONID的输出cookie,我们叫做session cookie,以区别persistent cookies,也就是我们通常所说的cookie,注意session cookie是存储于浏览器内存中的,并不是写到硬盘上的,这也就是我们刚才看到的JSESSIONID,我们通常情是看不到JSESSIONID的,但是当我们把浏览器的cookie禁止后,web服务器会采用URL重写的方式传递Sessionid,我们就可以在地址栏看到sessionid=KWJHUG6JJM65HS2K6之类的字符串。

        明白了原理,我们就可以很容易的分辨出persistent cookies和session cookie的区别了,网上那些关于两者安全性的讨论也就一目了然了,session cookie针对某一次会话而言,会话结束session cookie也就随着消失了,而persistent cookie只是存在于客户端硬盘上的一段文本(通常是加密的),而且可能会遭到cookie欺骗以及针对cookie的跨站脚本攻击,自然不如session cookie安全了。

        通常session cookie是不能跨窗口使用的,当你新开了一个浏览器窗口进入相同页面时,系统会赋予你一个新的sessionid,这样我们信息共享的目的就达不到了,此时我们可以先把sessionid保存在persistent cookie中,然后在新窗口中读出来,就可以得到上一个窗口SessionID了,这样通过session cookie和persistent cookie的结合我们就实现了跨窗口的session tracking(会话跟踪)。

        在一些web开发的书中,往往只是简单的把Session和cookie作为两种并列的http传送信息的方式,session cookies位于服务器端,persistent cookie位于客户端,可是session又是以cookie为基础的,明白的两者之间的联系和区别,我们就不难选择合适的技术来开发web service了。

    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)

    Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

    The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

    10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

    Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

    How to turn off private browsing authentication for iPhone in Safari? How to turn off private browsing authentication for iPhone in Safari? Nov 29, 2023 pm 11:21 PM

    In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode

    Win10/11 digital activation script MAS version 2.2 re-supports digital activation Win10/11 digital activation script MAS version 2.2 re-supports digital activation Oct 16, 2023 am 08:13 AM

    The famous activation script MAS2.2 version supports digital activation again. The method originated from @asdcorp and the team. The MAS author calls it HWID2. Download gatherosstate.exe (not original, modified) from https://github.com/massgravel/Microsoft-Activation-Scripts, run it with parameters, and generate GenuineTicket.xml. First take a look at the original method: gatherosstate.exePfn=xxxxxxx;DownlevelGenuineState=1 and then compare with the latest method: gatheros

    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.

    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.

    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

    See all articles