Getting Started with PHP Sessions

Getting Started with PHP Sessions

Introduction:

This tutorial is designed to teach about PHP Sessions, answering a few basic questions like: what they are, when and why you would use them, and how to use them. Additionally we will go over how to actually implement sessions into PHP code, and use them effectively.

PHP Sessions are used all over the internet to identify users. It’s how a website knows who you are, differentiating you from other users, and knows to feed you your data and not someone else’s. An important part of sessions are ‘Session Variables’, which are saved in a superglobal array (meaning they can be used across multiple web pages) and will last until the user closes the page (by default, but can be changed). Session variables can contain all sorts of data, but will typically contain things like your username or other identifying information. These session variables are stored on the web server rather than the user’s local machine which is good for security and privacy. The only thing that gets saved on the client machine is a cookie that contains the session id, or some other information the developer may specify.


Tutorial:?

Getting Started

As far as installation goes, sessions don’t require any additional libraries or extensions. Everything you need is built right into PHP already and is enabled by default. You only need an apache server, which can easily be configured locally using Docker, or in the Cloud using a Hosting Service (AWS, BlueHost, GoDaddy, etc.). For the sake of this tutorial, we will assume you already have your web server up and running, and we will not cover it in this tutorial.

Starting a Session

Okay, so you have your apache server up and running, with a PHP page ready to go. Starting a PHP Session is done by simply running? session_start(); in your code. A quick thing to note about sessions, is that they need to run before any actual HTML is run, as shown in the example below.

<?php
? ? session_start();
?>


<!DOCTYPE html>
<html>
<head>
? <title>PHP Session Tutorial </title>
</head>


<body>
  <h1>Index.php</h1>
</body>
<html>
        

Here the session is started properly by placing the session start before the?<html> tag. If?you fail to do so, you may see the error below.

Warning: session_start(): Cannot start session when headers already sent in /var/www/html/index.php on line 15        

This error often occurs because?session_start();?was placed in code within the?<html>?tag.?

Make it a habit to start the session very first when you begin writing a new page for your website. It is not too difficult to fix to make later, but sometimes the error message can be quite vague (like the one you see above), which can make debugging a cumbersome task later. So do yourself a favor, and every time you start a new page, make adding code for starting the session one of the first things you do before proceeding with the rest of your code.

There are a few predefined constants (a constant is a variable that never ever changes.) that come with PHP sessions that, while not required, you can use to make more error-free code and reduce headaches in the long run.

SID (string) - Contains either the session name and session ID in the form of "name=ID" or empty string if session ID was set in an appropriate session cookie. This is the same id as the one returned by session_id().

PHP_SESSION_DISABLED (int) - Return value of session_status() if sessions are disabled.

PHP_SESSION_NONE (int) - Return value of session_status() if sessions are enabled, but no session exists.

PHP_SESSION_ACTIVE (int) - Return value of session_status() if sessions are enabled, and a session exists.

(from Predefined Constants page)

What these constants are mainly used for is comparing against? session_status() to check the current state of the session. A great habit to use is the following:


// Check whether session started using Predefined Constants

if (session_status() == PHP_SESSION_NONE) {

????session_start();

}
        

This will check that a session doesn’t exist before starting a new session. If?one does already exist, there is no reason to start a new one. We’ll come back to this later in the tutorial, so if you don’t fully understand what is happening here, do not fret.

Session Variables

It’s great that we’ve started a Session, but... what do we actually do with it now that we’ve started it? This is where session variables come in. As mentioned earlier, session variables are stored in a superglobal array named? $_SESSION ?and uses the typical array syntax as follows:

$_SESSION[“<variable_name>”]

Where <variable_name>?is replaced by whatever variable you decide. This could truly be anything from ‘favoriteColor’ to ‘nameGrandmaDog’, but you will most often find things like ‘name’, ‘username’, ‘user_id’, ‘session_id’ and so forth.

Now, what differentiates the superglobal array from a normal array, is that it persists across php pages. Check out the example below, where we set a session variable for ‘name’ and then use the same variable on a different page.


<?php
? if (session_status() == PHP_SESSION_NONE) {
? ? session_start();
? }
? $_SESSION["name"] = "Robert";
?>


<!DOCTYPE html>
<html>
<head>
? <title>PHP Session Tutorial </title>
</head>


<body>

<?php
? ? $user = $_SESSION["name"];
?>

<h1>Index.php</h1>
<p> Hello, <?=$user?> </p>

</body>
</html>
        
No alt text provided for this image

As shown, we’ve set the session variable “name” to Robert, and then in the HTML we will print it out in a nice greeting. This is great, but let’s create a new php page and try it over there.


<?php
? if (session_status() == PHP_SESSION_NONE) {
? ? session_start();
? }
? $page2user = $_SESSION["name"];
? $_SESSION['test'] = "test";
?>


<!DOCTYPE html>
<html>
<head>
? <title>Page 2</title>
</head>


<body>

<?php
? ? $page2user = $_SESSION["name"];
?>

<h1>Page2.php</h1>
<p>Welcome to your other page, <?=$page2user?></p>

</body>
</html>

        
No alt text provided for this image

And we see that this session variable carries over to our second page. Can you see the power of session variables?

Ending a Session

If you want to get rid of a specific session variable, you can use the unset(); function, placing the session variable you’d like to destroy as a parameter, like such:


unset($_SESSION[‘variable’]);        

When you are completely done with a session (like logging out a user), then the easiest way to end the session is with?session_destroy(); which will destroy all current session variables and values, and then terminate the session.?

Other Useful Session Functions

session_status(); This function will return the status of the session. Remember the predefined constants from earlier? Well this function will return those values. This is an easy way to check if sessions are: disabled, enabled there is no active session, or if there is an active session. You can use this to handle cases, so you don’t accidentally create new sessions that already exist, or start sessions when they’re disabled and cause errors.

session_id(); Every time you start a new session, it will generate a unique session ID to identify the user and their session. There are many cases where you might need the session id, and this is a handy function to retrieve it. Or, equally as powerful, if you put in a parameter in the parentheses, you can set the session_id to whatever you want, but to do so you must run the session_id(<id>)? function? BEFORE you start the session.

session_regenerate_id(); This will update the current session id with a newly generated one, while keeping all the current session information, values, and variables. It essentially makes a copy of the old session. This can be used to duplicate users/projects. There is a parameter for? delete_old_session,? which does exactly what it sounds like- creates a new copy of the current session, and then deletes the old one. This method is not recommended, because in cases with unstable internet, the old session may be deleted without the new session being created, resulting in a terminated session. This can be used to change the session id one each login if desired.

session_reset(); This function which takes no parameters will reset all session variables and values to what they were at the beginning of the session. This is handy if you are building a page that gives users the option to cancel or revert any changes. It’s essentially pressing the ‘cancel’ button at the bottom of a page.

session_abort(); Similar to the ?session_reset();? function, but it will also terminate the session after. There is no need to do a? session_destroy();? after calling session_abort();

(from Session Functions page)

Why Sessions over Cookies?

Cookies play a similar role in storing user related data. The main concern with cookies, and why you would choose PHP Sessions over them, is the concern over security. Because cookies are stored locally on the user’s computer, they are left vulnerable to be manipulated and modified by attackers.?

Another concern is one of performance. Cookies have to send user data each time the user views a page or switches pages, and all that information has to be sent through an HTTP request. Since PHP sessions are stored on the server, they do not have to be transmitted each time you load a webpage.

Additional Use and Research

One thing we did not go over but which can be very useful in conjunction with PHP Sessions, is tying in a Database server. Doing so will allow you to create user sessions that permanently save to the server, and can be resumed later. Without going into too much detail, you can attach session variables to values from the database (like username, user_id, address, phone number, etc.) to use throughout the website. This is a topic you should look into further, now that you know more about PHP Sessions.


Additional Resources:?

W3Schools PHP Sessions - a basic guide to help get started with PHP Sessions and Session Variables. It is super rudimentary and will not help beyond the basic use case: https://www.w3schools.com/php/php_sessions.asp

Geeks For Geeks page on PHP Sessions - This is a little more in depth than the W3Schools page. It gets into why you would use a PHP Session over a similar method like Cookies. But again, it is fairly basic and only covers the basics to get you started: https://www.geeksforgeeks.org/php-sessions/

Tutorialspoint page on PHP Sessions - This page provides some basic detail specifically about what is actually happening when you create a PHP session to make it work, and going a bit more over session id’s: https://www.tutorialspoint.com/php/php_sessions.htm

Robust documentation about PHP Sessions - This is a very useful documentation page straight from PHP.net and contains most (if not all) you need to know about PHP sessions: https://www.php.net/manual/en/book.session.php

要查看或添加评论,请登录

社区洞察