Getting good with php

Page 89

89

Chapter 4

Sessions Perhaps cookies are a little too persistent for what you have planned. Let’s say that you want be able to set values that you can use across several pages (and not pass them back and forth), but you don’t want them to be remembered beyond the user’s visit. For example, you know how many websites have a “remember me” checkbox when you’re signing in? If you check that box, they’ll store the login info needed to keep you from having to log in on every page as cookies. However, if you don’t check the box, they want to store the information temporarily; just for your visit. After you close the browser, they want that information to be lost. This is where sessions come in handy: they store whatever info you give them only for that browsing session: once you close the browser, your “session” is over and all session information is gone. So, how do we create and use sessions? Well, it’s pretty different from cookies. On any page where you plan to use session variables, you start by calling: session_start();

I should note that even if you just want to read (and not write) session variables on a given page, you still have to call that function. After that, you can just set and get items in the superglobal array $_SESSION. Session variables will persist until the user closes their browser. Here’s a simple example: Example 4-6 <?php session_start(); if (isset($_GET["name"])) { $_SESSION["name"] = $_GET["name"]; ?> <p>Thanks! <a href='e4-6.php'>Go here for your message </a>.</p>


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.