How to Code PHP Sessions & Cookies

In this article I’m going to talk about using cookies and sessions in PHP. I’ll provide many examples to help you learn how to code PHP and then in the next article run you threw some PHP code you can use on your own sites.

Cookies & Sessions

There are two main ways for you to store information on your visitors and create a dynamic site. Cookies are used to store information on the visitors computer. Much like you do with arrays, cookies are stored as a key value pair.

Many people are afraid of cookies, because they think those websites that use them are tracking their every move. For this reason it may be hard to serve up the dynamic content that you want. There are work arounds for those visitors that have cookies shut off as you’ll soon see.

Creating a Cookie

Cookies must be sent before any other HTML code, or an error will be thrown. So, make sure your PHP code is the first thing the browser sees before any HTML code. Websites have even been banned, if they make this common error. Don’t worry, I’ll show you exactly how to set them.

You create a cookie with the setcookie() function. It’s general structure is: setcookie(var_name, value, expiration_date, path, domain, security); You could create a cookie by just defining a name an value like this example: setcookie(‘first_name’, ‘George’);

The other data you could save includes:

  • Expiration: Tells the browser how long you want the cookie to exist. If not set the cookie will be stored until the browser is closed, so you probably want to set this value. If you entered the following as a value of expiration time()+3600, the cookie will exist for one day. (60 seconds x 60 minutes = 3600)
  • Path & Domain: Define who can access the cookie data. This limits other web sites from seeing your cookies.
  • Security: Allows you to set that the cookie data should only be sent over a secure HTTPS connection. If the value of 1 is set then a secure connection is required.

You can set as many cookies as you like, with repeated calls to the setcookie() function. The variable name in this case does not start with a $, like other PHP variables, but it also cannot contain spaces, and is case sensitive.

It is common to create cookies that reference the visitor’s name, userid, products they had in a cart, email, etc. I leave it for you to decide what you will store in cookies. You just have to remember these rules:

  • Cookies can only contain 4 kb of data
  • You can only store 20 cookies total, on a visitor’s computer

Getting Cookie Data

After you create a cookie, it’s easy to check if a new visitor has any cookies saved on their computer when they return. Just check for cookies with a reference to the key name you set with the setcookie() function:

if (!isset($_cookie[‘first_name’])) { // Perform Actions }

This is statement will check to see if you stored a variable (key), on the visitor’s computer. If you find it, perform what ever actions you like. If not, make sure you provide another appropriate action, such as set a cookie?

After you know the cookie has been set, you’ll be able to retrieve the value by referencing the cookie array. All of the cookies you set are available by calling $_COOKIE[‘first_name’], for example. Just place the name of the key in the $_COOKIE[] array and then you can do what ever you’d like with that information.

Deleting Cookies

To delete a cookie just set the value to nothing with the setcookie() function, like this setcookie(‘first_name’).

That’s just about all there is to know about cookies. Now I’ll explain how to use sessions in PHP.

Sessions

The difference between cookies and sessions is that visitor information is stored on your server with sessions. You can store an identification number in a cookie, or you can use sessions without cookies, by sending a session id from page to page. I’ll explain all of this with a few examples.

Advantages Over Cookies

  • They allow you to store a lot more information than cookies
  • They are more secure, because the information is stored on the server
  • If the visitor has cookies shut off, you can still gather information

Disadvantages

  • Cookies are easier to work with
  • Using cookies are slightly quicker

Creating a Session with a Cookie

You start a session by calling the function session_start() at the beginning of the file, just like you did with the cookie. When this function is called, it will send a cookie with the session ID, called the PHPSESSID. The ID will be a series of 32 numbers and characters.

Creating Variables and Assigning Values

You create key value pairs with statements like this: $_SESSION[‘first_name’] = ‘Paul’; Here I’m creating the key, or variable and assigning the value of Paul.

Accessing Session Variables

When a visitor returns to your site, you can check for the set cookie and then access those variables previously stored on your server. Here is how you check for the cookie:

if (!isset($_SESSION[‘id_num’])) { // Perform Actions }

If this statement comes back as true, you can perform your series of actions with the session. You would then access those stored values by calling for the values stored in the $_SESSION array. Here is an example: echo “The First Name is {$_SESSION[‘first_name’]}”

Deleting Session Data

There are three PHP functions you can use to eliminate session data. The function unset() to delete a single variable, like this: unset($_SESSION[‘first_name’]);

You delete every session variable with the following statement: $_SESSION = array(); And, finally the function session_destroy(); will eliminate all session data.

Using Sessions without Cookies

The main benefit you will gain from using sessions, is that you can store information on your visitors, even if they have cookies set off. Like I noted before, you accomplish this task by passing the session id from page to page.

The value you append to the end of the url, is called a session ID and is stored in a constant variable you define in your code with the name SID.

To use sessions in this way, you can’t use cookies and also you have to tell the browser to not use cookies with this statement: ini_set(‘session.use_cookies’, 0); Also, when your user clicks a link or you call for the user to go to a new page, append the SID at the end of the url.

You can access the variables in the same way you did before when you used cookies and sessions together.

That’s All Folks

In the next article I’ll go further into how to code PHP, with a bunch of sample scripts you can use on your own sites. If you have any questions leave them in the comment section below.

Till Next Time

– Think Tank

Leave a Reply

Your email address will not be published.

Google+