Sign In | Subscribe

Enter your Sign on user name and password.

Forgot password?
  • Follow us on:
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Advanced PHP
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Lecture Comments (1)

0 answers

Post by Elwin sylvester on September 11, 2012

This was the most helpful tut I've seen when it came to sessions. Thanks.

Introduction to Sessions

  • On the web, a session refers to a series of related communications between a web client & web server over a specific period of time that are used to:
    • Link multiple HTTP transactions
    • Preserve data over multiple transactions
  • Data, or state, preserved between a series of related HTTP transactions is referred to as session data.
  • A client-side session is when session data is stored by the web client, typically using cookies.
  • A server-side session is when session data is stored by the web server, typically in a file, database, or in RAM.
  • A unique session ID, or SID, is generated by a web server for each new server-side session.
  • The SID is used by the server to:
    • Identify multiple HTTP transactions as being part of the same session
    • To access any data stored for the session
  • A client passes an SID to the server with each HTTP request via either:
    • Cookies
    • URL Parameter
  • PHP typically uses a cookie, known as a session cookie, to pass the SID of a session between the client & server with each HTTP request.
  • PHP stores session data in flat files in the directory specified by the session.save_path configuration directive.
  • session_start() either creates a new session or continues an existing session. If using cookie-based sessions, it must be called before any output is generated.
  • $_SESSION is a superglobal used to store all session data and can be used to store data of any type, including arrays and objects.
  • When a key/value pair is added to $_SESSION, the key's name is referred to as a session variable.
  • To set, get, or delete session variables, standard associative array square bracket syntax & the unset() construct are used on the $_SESSION superglobal.
  • There are a number of configuration directives related to sessions in 'php.ini':
    • session.cookie_lifetime – sets the expiration of a session cookie
    • session.cookie_domain – sets the domain a session cookie is valid for
    • session.cookie_path – sets the path a session cookie is valid for
    • session.use_cookies – sets that cookies should be used to transfer SIDs
    • session.use_trans_sid – sets that URL parameters should be used to transfer SIDs
    • session.use_only_cookies – can be used to enforce the use of cookies for transferring SIDs
  • Additional Resources:

Introduction to Sessions

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Lesson Overview 0:08
    • Lesson Overview
  • What is a Session? 0:53
    • What is a Session?
  • Client-Side Sessions 3:51
    • Client-Side Sessions
  • Server-Side Sessions 5:04
    • Server-Side Sessions
  • Session IDs 6:26
    • Session IDs
    • The SID is Used by the Server to:
    • A Client Passes an SID to the Server with Each HTTP Request Via:
  • Sessions in PHP 12:19
    • Sessions in PHP
  • session_start() 14:40
    • session_start() Overview
    • Coding Example: Using session_start () to Continue a Session
  • $_SESSION Superglobal 22:06
    • $_SESSION Superglobal Overview
    • Coding Example: Setting a Session Variable via $_SESSION
  • Accessing Session Data 28:08
    • Accessing Session Data
  • Deleting Session Data 31:43
    • Deleting Session Data
    • Coding Example: Deleting Session Data
  • Configuring PHP Sessions 36:14
    • session.cookie_lifetime, session.cookie_domain, and session.cookie_path
    • Coding Example: Configuring PHP Sessions
  • Configuring PHP Sessions (cont.) 40:56
    • session.use_cookies, session.use_trans_sid, and session.use_only_cookies
    • Coding Example: Configuring PHP Sessions
  • Homework Challenge 42:55
    • Homework Challenge: 1 - 5
  • Homework Challenge (cont.) 44:10
    • Homework Challenge: 6 - 10
  • Homework Challenge (cont.) 45:27
    • Homework Challenge: 11 - 13

Transcription: Introduction to Sessions

Hello again, and welcome back to's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be introducing the concept of sessions.0005

In particular, we are going to be going over what a session is.0010

And then, we are going to talk about two different ways that you can manage sessions.0013

One is a client-side session; one is a server-side session.0017

Then, we are going to talk about how to implement sessions in PHP (which is a type of server-side session).0021

And that is going to involve a discussion on what a session ID is, how sessions work in PHP, a couple of methods,0028

and a new superglobal we are going to introduce that allows you to work with sessions in PHP.0036

And then, we are going to talk about how to access and delete data within a session, which is the state of a particular session.0041

And then also, we are going to finish up with some comments on how to configure sessions in PHP.0048

First, what is a session? Well, on the Web, a session refers to a series of related communications between a web client and a web server.0055

For example, when you log into a website (for example,®) and go shopping, and you have your shopping cart,0065

when you add an item to your cart, and you go to the next page, and you add another item to your cart,0073

each of those separate HTTP requests, or transactions, are linked together.0078

The website knows that, when you add an item to your cart, and you go to the next page0085

and add another item to the cart, both items will be in the cart.0089

It links those together, and it does so over a specific period of time, as well (which is another key element).0093

Sessions are defined both by the two parties communicating (a session occurs0100

between a particular web client and a particular web server), as well as a time period.0107

Sessions are time-relevant: for example, maybe you have a banking website that you have gone to, and it will give you a warning,0113

after ten minutes, that your session is about to time out.0117

What that means is that sessions have a temporal element to them, and they are confined0121

to not only communication between two parties, but also communication between two parties over a certain amount of time.0126

Now, that time could be something that times out, and a session automatically ends;0132

or it could be something that...a session can be explicitly ended, either by a server or a client.0138

Sessions are used to link multiple HTTP transactions.0144

An example of that would be when you log into a website with your username,0149

and then each page you go to on the website might say "Hello, Matthew," for example, at the top of the page.0152

It knows that you have logged in, and that your name is Matthew.0157

And so, every time you view a new page, it is linking those HTTP requests and responses together0161

to know that they are all part of a single session.0167

Additionally, sessions are used to preserve data over multiple transactions.0170

A perfect example of that is a shopping cart: when you add multiple items to a shopping cart,0175

you might do so on two or three different PHP pages, for example.0180

Well, when you finally go to view the cart to checkout (let's say you added three items to your shopping cart),0185

in order to keep track of all of that, that state has to be kept somewhere.0192

The session has to know that you have added, maybe, item 1001, 1002, and 1003, to your shopping cart.0198

Because HTTP, as we learned in our lesson on cookies, is a stateless protocol, it doesn't know,0204

between one HTTP request and the next, about any other HTTP requests; we have to maintain that state somewhere.0211

Data, or state that is preserved between a series of these HTTP transactions0220

(for example, adding multiple items to your shopping cart) will be referred to as session data.0226

Now, what you may have realized in just that short description of sessions is that we have actually already been implementing a type of session.0233

We have been implementing a client-side session.0239

And we have done that in our web store application, where we used cookies to track the status, or the state, of a particular shopping cart.0244

Every time a user added a new item to their shopping cart, we would set another cookie0254

with an item that has the cookie's name as the item ID, and then set its value equal to the quantity added.0258

And we would update, add and delete, and move these cookies in order to maintain the state of the shopping cart.0264

This is called a client-side session, because the state data, or the session data, is stored on the client.0270

In this case, it is stored in the form of cookies, which, as we know, are name/value pairs0279

that a server sends to a client, that a client will save somewhere on the client computer, storing that data.0285

And then, it will send that information back to the server on each request.0293

This is typically accomplished via cookies; and that is known as a client-side session.0298

A server-side session (which is what we are going to be discussing, and what is the functionality that PHP provides)0306

provides the same sort of functionality, except that the session data is going to be stored by the web server.0311

So, instead of storing your shopping cart data in a bunch of cookies on the client side0318

that get passed back and forth between the client and the server, your session data is going to be stored on the server,0322

typically in a file, or maybe even a database--or maybe even in RAM.0328

If there is a limited number of users connecting, you might have the capacity on your web server0334

to just store all of a client's information in RAM.0339

Instead of having a cookies that might be called 1001=1, you might have a text file somewhere called...that stores that same text data.0343

This is the file name, and this would be the file contents, which would be the same thing.0370

This information could also be stored in a database, and RAM as well.0376

Now, we are moving the state of the session from the client into the server.0380

Typically, the way server-side sessions are implemented is by making use of a unique session ID, known as an SID.0388

And what that is: every time a user starts a session--it connects to a web browser and says, "I want to start a session"0396

(for example, it logs into a website), the web server is going to generate this unique ID.0402

It is typically a long, random number and letters that is considered unique enough0407

to uniquely identify that user and this particular time that it is connecting to the web server.0416

The web server will generate this SID, and it uses that SID, that unique ID, to do two things,0424

which is part of what we just explained as part of sessions.0436

It is used to identify multiple HTTP transactions as being part of the same session.0441

For example, when you add multiple items to a cart, what is going to happen is:0447

the session ID (SID) is going to be sent to the server with each request, every time you add an item to a cart.0451

And the server is going to be able to know then, by looking at the SID provided,0461

that those requests are supposed to be linked together; they are part of the same session.0465

It is also going to be used to access any stored data for the session.0470

For example, if you have this unique SID, and you send a request to the server, and you are trying to load up some data0474

that you had stored (maybe the state of your shopping cart), the server knows how to take this SID0484

and then use it to access any session data that has been stored on the server.0489

What happens (as was mentioned) is: the client passes this SID to the server on each request.0496

So, what happens is: when a session is started, the server sets a cookie with some unique ID, and it sends it to the client.0503

For example, let's say the client logs in; the server says, "OK, this is a valid login; now I'm going to start a session."0520

And it is going to send this cookie to the client.0525

Well, now every time the client goes back and requests a file from that particular website,0527

it is going to include the Cookie header in its HTTP request, which is going to pass along this SID.0532

So now, every time the web server receives a request from the client, it is going to have this cookie.0540

And the server is going to be able to say, "OK, this is part of this 1ABE session that is currently going on."0544

And it will be able to link to multiple transactions, and then also, it will be able to access any data associated with this (for example) 1ABE session.0552

We know that we can do this via cookies; and what happens is: there is only one cookie that is passed back and forth between the client and the server.0563

In our web store application, we had the server setting multiple cookies on the client--one for each item in our shopping cart--and that was to maintain state.0575

Well, now all we need to do is pass this unique ID back and forth via cookies.0583

And by presenting that unique ID to the server on each HTTP request, that is going to allow the server0587

to get all of that state information that is already stored on the server.0594

Another option would be to use a URL parameter.0597

For example, we know that we can pass GET variables by appending them as query strings to a URL.0600

For example, let's say that we wanted to get a script called addItem, which adds an item to a cart.0609

We might be able to append the SID...for example, let's say we want to add item 1001, and this is the format that we use in this addItem script.0619

Well, what we can do is append this SID to each time we request a URL via GET from the server.0637

And what that is going to do is: then, when this information comes in, PHP is going to be able to extract this SID0649

and then know how to access session data, and also to link the transactions together.0655

This is not a secure method, and it is generally not recommended to be used.0660

So, all of the sessions that we are going to be doing within this course are going to make use of cookies.0668

And as we mentioned in our last lesson on cookies, that means that for users to use your website0673

(that has sessions that use cookies), they need to have cookies enabled on their browser, so that is one thing to consider.0680

And mainly the reason that this is considered insecure is because any time you have a URL, you could bookmark it.0686

For example, you could email your URL to a friend.0691

Well, if your URL contains your session ID, then that means that that person can just click on that link,0696

and if your session is still valid (let's say the session still hasn't timed out yet--and we are going to talk0701

a little bit more about the lifetime of a session), if that user clicks on that and provides that SID,0705

the web server is going to assume that it is you.0710

And then, that person is going to have access to your account.0714

That is why it is not used--one of the security reasons.0718

It is a lot more difficult to do that with cookies--if your friend wanted to be able to impersonate you in the same way,0721

and it wasn't using a URL parameter, they would have to have access to that cookie0728

that PHP set on your computer, and then be able to send that over, which is more difficult to do.0732

As mentioned, server-side session functionality is built into PHP.0742

And PHP typically uses a cookie; as mentioned, it can use URL parameters, but the preferred method,0746

and the method we are going to be using, is to use a cookie.0752

And that cookie is going to contain the SID of a particular session.0754

And this cookie that contains the SID is sometimes referred to as a session cookie.0759

And what that enables us to do, as we had mentioned, is: it is going to allow that SID to be passed0766

from the client to the server on each request, so that a client can identify itself as part of a particular session.0771

Now, when that server receives that cookie from a client, it is going to be able to look up some session data for that server.0778

Well, in PHP, we had mentioned earlier that using server-side sessions, a server could choose to store session data in files.0786

Maybe it has a separate file for each session; it can store it in a database; it can store it in RAM.0796

Well, in PHP, session data is stored in flat files, or just text files.0801

And what it does is: for each unique session that is initiated, it is going to create a file in which to store any session data.0808

It stored these files in the location specified by session.save_path directive.0820

So, whatever that directive is set to in your php.ini file--that is where these temporary session data files will be stored.0828

In XAMPP (which is what we are using in this course), by default, this save_path directory is set to the tmp directory of your xampp root directory.0837

We can go and look at our php.ini file, and we can see that there is a section within php.ini that discusses configuration options related to sessions.0848

And we can see that session.save_path is set to C:Users/Educator1/xampp/tmp, which is saying that0861

any time data files are created for a new session, they are going to be stored0869

in the tmp directory of our xampp directory, which we have stored in our user directory.0873

Any time you want to have a script that uses session functionality, you need to call a built-in function called session_start.0883

And what that will do is: whenever that is called on a script, it will test to see if a session currently exists.0892

And the way that it does that is: it checks to see if the user, when they are requesting a particular page,0898

has passed an SID to that script by either a cookie or a URL parameter.0902

If not, it creates a new session, which is going to involve generating a new SID.0907

And then, when it returns the response from that particular script back to the user, it is going to set that cookie to the user.0911

Or if it does find an SID in the client's request, then what it is going to be able to do is continue the existing session.0917

And it is going to be able to do things like access any previously stored session data.0925

As mentioned, session_start is going to generate an SID, and will send a cookie to the client with that new ID, if the session is new.0930

And the value of the cookie that it sets is the configuration directive in php.ini.0940

If we look at php.ini, the default in PHP and in XAMPP is to name a session PHPSESSID.0954

Any time you start a new session with PHP, with a default setup, when a script calls session_start for the first time in a session,0964

a cookie is going to be sent back to the client that is going to be called PHPSESSID.0976

And it is going to be set equal to whatever random session ID was generated--for example, just some random string that it comes up with.0985

If a session is being continued, what session_start is going to do is look for a URL parameter or a cookie that is named

So, it might be a GET variable called PHPSESSID=.... if this was a URL parameter.1006

Or it would look for a Cookie header in an HTTP request that will have a cookie named PHPSESSID1023

equal to whatever the random session ID was, assigned to this previously-started session.1033

What it can do is use that session ID, then, to access any previously-stored data, which we are going to talk about in a minute.1040

One thing to note is: if you are using cookie-based sessions (which, again, is the typical scenario used),1047

you must call session_start before any output is generated for your script.1053

And the reason for that is that, because this session_start method will send a cookie to the client when a new session is created,1058

it is going to be setting a header, the Set-Cookie header, and it is going to be calling the setCookie method.1068

And as we have learned before, any time you want to add HTTP headers to a response you are sending back to a client,1074

you need to do so before any output is generated.1081

Let's take a look at an example that we have.1085

It is two scripts: one is called sessionStart.php, and what it does is just calls this session_start method,1088

which says, "When the user views this script, it is going to start a new session."1096

So, when the user requests this page, if an SID hasn't been provided by a cookie, for example, it is going to go ahead and generate an SID.1100

And then, it is going to set that PHPSESSID cookie, and it is going to send it back to the user with the response.1109

And in this case, the content of this script that it returns to the client is just some information about the request sent by the client,1116

and then also information about the response header sent by the server.1125

It uses a couple of methods here: getHttpResponse and getHttpRequest, which are just functions that I have created.1130

When you look at the lecture_examples directory, you will see that there is a file called utilLIB.php.1138

And what it does is: it goes ahead and builds up this string that represents an HTTP header response.1142

We can quickly see what is going on when a session is started, as far as cookies go.1149

So, if we go and load this page, example1, and we click on start_session, for example,1155

if we look down here at Firebug before we load the script, we can see that currently there are no cookies1163

being sent by the client when it is making a request to the web server.1169

That means that no cookies are set for this particular path and this particular domain.1175

And you can see that by looking at the HTTP request.1182

Now, when we request sessionStart.php, we can see a couple of things.1184

First of all, we can see that when the client requested the page, it requested sessionStart.php,1190

and it didn't provide a cookie, because no cookie existed for this domain and path.1195

However, when we received our response back, we can see that the server did set a cookie.1200

It set a cookie called PHPSESSID, as we expected.1206

And then, as we can see, it set it to this random string of letters and numbers.1209

And it also specified a path for this particular cookie.1213

And so, if we look down in more detail at the request and response headers, we can see that,1217

when the user requested the page, there is no Cookie header, because no cookie was previously set.1227

However, when the response came back, there is a Set-Cookie header that was provided by the server.1233

So now, if we go to look at a second page, continueSession.php, what this is going to do is be another page that is going to continue our session.1240

And so, all it does is: at the beginning, it calls session_start.1250

What is going to happen is: now that our client has had a PHPSESSID cookie set, when it requests this new page,1253

it is going to send that cookie along, because this is in the same directory, so its domain and path of that cookie are going to match.1259

And then, what is going to happen is: PHP is going to know that it is part of the same session.1265

So, what we are going to see is that, when we look at the response from this method,1269

the server is not going to send back a setCookie parameter, because when it calls session_start,1274

it can already see that there is a cookie that has been created.1280

If we go to continueSession, we can see that, in our request, we have now passed along this PHPSESSID cookie1283

that was generated by the server and was set on the client.1291

So now, we have identified to the server, when we requested continueSession.php, that it says,1296

"Hey, we are part of a PHP session, and this is the ID that we have been assigned for this particular session."1302

Now, when the response from the server comes back (which is just the output of this page),1308

we can see that the setCookie parameter is empty; there is no Set-Cookie header.1312

And that is because it doesn't need to set a session cookie, because it already detects one.1318

And so, that is how a session would be continued.1323

One thing that session_start also does is has the effect of making session data available in a script via this superglobal variable $_SESSION.1329

When you call session_start, if a session has already been created, it recognizes an SID via a cookie.1341

Then, what it is going to do is populate this superglobal array session with any session data that has been previously set.1347

For example, you may have added an item to a shopping cart.1354

And what you do is add that item to a previous script, where you accessed session, you may have saved an item to a shopping cart.1357

And you do so by directly accessing this $_SESSION associative array.1365

It is an associative array, and you add data to your session simply by adding key/value pairs to this $_SESSION superglobal.1372

For example, let's say we wanted to add a session variable called username, or we want to add session data that represents a user's name.1380

We can set a key called username in the _SESSION superglobal, and then set it to a string.1388

In this case, it is jsmith, which maybe is a username for a particular user.1394

In this case, username is what is known as a session variable.1399

When you add session data to this _SESSION superglobal, the key that you use is called the name of the session variable.1404

In this case, we are saying we are creating a session variable called username; we are setting it equal to the value jsmith.1416

And one thing to note is that the keys have to be strings, just like in any other associative array;1424

but the values can be any data type--they can be objects or even arrays.1429

So, you can store whatever you want in there--you can store any kind of data.1434

And you can store as much data as you need to within the _SESSION superglobal, simply by adding new keys...1436

for example...I don't want to do password, but...maybe you would add a name session variable that represents the name of the user.1445

So now, every time you go to a page, session_start is called at the beginning of that page.1459

An SID is going to be recognized by PHP.1464

It is going to go out and load that session data associated with that session ID, and populate it into this session variable.1467

The way that it does that is: it loads the data stored in the session's data file, which is stored in session.save_path.1476

We talked about...each time a new session is created in PHP, there is a temporary directory in which PHP will create1485

a data file in which to store any session data.1491

Any time you set session data, for example, via this method here, what happens is:1494

when that script ends, PHP goes and updates this data file that is associated with this particular session.1499

And then, the next time, when you come back to request another web page, when you pass it the SID,1506

it can use that SID to go up and look up that particular data file, and then load the data out of it into this _SESSION array.1512

And we are going to take a look at how that works.1519

For example, if we go and look at example-2, one thing that we can see is that the default path1523

in the PHP setup for a session cookie is / , which means anything on the domain that the cookie was set at, which in our case is localhost.1533

We can see that our cookie is still being passed along, even though we are on a different example,1544

because we are still under the root path of this particular domain.1550

In order to do this example, we are going to need to delete the cookie.1555

And one of the ways you can do that is just a shortcut to clear your recent history in Firefox.1558

And we can say, "Delete all the cookies from the last hour."1564

So, if we clear that, and now if we refresh the page, we can see that there is no Cookie header,1568

so we are no longer passing a session cookie to this page.1575

What we have is a script called setSessionVar, which is a script that starts a session.1579

So, it is going to generate this new SID, which it is going to send back to the client with this response.1587

And then, it is also going to add a session variable called username and set it equal to jsmith.1591

And then, it is just going to output a little message and a link to a page that is going to allow us to view a particular session variable.1597

When we go ahead and load this setSessionVar page, what we can see is1605

that we have had a Set-Cookie header sent back to us with a new PHPSESSID cookie value.1612

And so, here is another random string; and that is what we are going to use to identify ourselves in this new session.1621

Now, if we go and look at our xampp directory, and we look at the tmp directory (which we had talked about),1627

we can see that there are a bunch of files here with random names.1638

They start with sess_ , and then the name of the session ID that is generated for a particular session.1643

So, any data we store for a particular session gets stored in a data file that has a name that includes the session ID as part of the name.1649

So, if we look at our session ID generated, it was hgjc8t, for example--that is what it begins with.1657

If we look at our directory, we can see: here is a session file hgjc8t, and so on.1666

So, that is a data file that was created when we called session_start.1673

That is another thing that happens when you call session_start: it goes ahead and creates a session data file.1678

And it is able to look it up via the session ID.1684

The way that we access session data is: what you need to do is: on any script1690

where you want to access data that has previously been stored in a session, you need to call the session_start method.1694

And the reason for that: what that is going to do is load any data that you have previously stored in your session1700

from that session's data file, which is identified by the SID.1705

And it is going to load it into this _SESSION superglobal.1709

So, any variables we have previously set..for example, we have previously set the username variable in this;1713

well, now we are going to have access to it.1718

And the way you do it is simply the way you would access any other associative array or superglobal.1720

You have the name of the array, and then, using the square bracket syntax, you specify the variable's name.1725

Our session variable username, which we associated with the value jsmith...1732

when we call this echo statement on a script where we have also already called session_start,1739

and we have previously set the username to jsmith, this statement is going to echo1744

the string jsmith, which is going to load from the _SESSION array.1749

If we go and look at...1753

Well, our setSession script has a link that says Next Page, which links to a page called getSessionVar,1756

which we are going to use to demonstrate how to access session data.1763

If we go look at getSessionVar, we can see that, beginning at call session_start, because you have this cookie now1767

that you have passed along, because you have started a session when you request this page,1773

you are going to be passing along that session cookie that was generated--that hgjc8t...whatever ID it was.1778

Well, when this method is called, it is going to read that cookie.1784

It is going to be able to go to our temporary directory, load any data that is stored in that file, and then populate the session with it.1787

And one of the things we can do is look at this file.1796

And we can see that it has some information.1811

Since we have already set a variable to it, we can see that it has an encoding that PHP uses1813

in order to serialize--take this data that we are storing as a session and serialize it so that it can be stored in a file.1820

So, we can see here that in this terse way, we can tell that we have a username variable called jsmith.1829

In this particular case, to decode this, it is saying that there is a username variable; it is a string of length 6; and the value is jsmith.1836

Any time you add data to a session, it is going to get added to this file.1845

So, there is encoded text within that file.1849

What is going to happen is: session_start is going to load that data that we just saw in that session file into the _SESSION array.1856

And now, we can access it; and we can go ahead and output session with the key name username.1863

And it is going to output that username that we had previously set, which is jsmith.1870

If we go and click on Next Page, we can see that we have been accessing the session variable username.1875

And we can see that it was able to access jsmith, which we had set on the previous script.1882

Also, notice that, when we called session_start, there was no set Cookie header,1885

because when we requested this page, we already passed along this hgjc8t session ID cookie.1891

It knows that a session has already been started.1899

We have learned how to add session data; we have learned how to access session data;1904

now, we are going to talk about how to delete it.1908

The way you delete data is the same way that you would delete data from any other associative array.1910

You can just call the unset method on the _SESSION superglobal and specify the name of the variable for the data you want to delete.1915

For example, to delete this session variable username, we simply call unset on the _SESSION superglobal, with the key set to username.1925

We have another script that getSessionVar is going to forward to when we go to Next Page.1937

It is going to go to a script called deleteSessionVar; and if we look at our deleteSessionVar script,1943

we can see that it starts the session--and again, this method has to be called in order to get access to the session.1948

It is kind of counterintuitive, but to delete a session variable, we have to start the session to gain access to it.1956

So, this is going to give us access to the _SESSION superglobal.1962

And here, we are deleting the session variable username by calling unset on _SESSION with the key username.1966

Now, when we go to try and output this session variable username, because it has been unset--1972

no longer exists--we are going to get an error down here.1978

And if we go and click on Next Page, we can see that there has been an undefined index.1980

You have tried to access username in _SESSION, and it doesn't exist.1986

What we can do is a ternary operator to just clean up this code a little bit.1991

We are going to test if the session variable is set, which means, "Does that session variable exist?"2005

If it is, we are going to set this variable username equal to the value it is set to.2011

And if not, we are going to set it equal to, let's say, 'does not exist'.2017

So now, when we reload our script (I need to update this part here to output this new username variable),2024

instead of getting this ugly message, it is going to say (oops, it looks like I left out a square bracket)...2034

we can see that we get an output that says, "This value does not exist."2053

Now, one thing to note is that that only deletes this particular session variable, username.2058

Let's say, for example, on our getSessionVar, we add another session variable.2063

Let's say we create a session variable called name and set it equal to Joe Smith.2070

Now, if we go back to getSessionVar and we re-click on the link and we reload the page, it is going to create this new session variable.2080

When we go to click on deleteSessionVar again, it is going to unset username,2089

but that other one will still be available, because we have only unset that one.2095

So, when we go down here, we can also echo this second variable.2097

And I am not going to use a ternary operator to test for it, because we know it is going to exist.2114

What we do is: if we go back to this page, it is going to reload the page...2118

Again, because we have unset that previous username session variable, it is not going to be able to output that.2123

But what we can do is: when we go back to our deleteSessionVar page, what it is going to do is:2130

it is going to have this new name variable created.2135

And so, it is going to output the username, where, in this case, the string says 'does not exist.'2140

But it is also going to have access to Joe Smith.2145

That is just a comment that lets you know that unset only unsets that particular variable.2147

And it sort of makes sense; it is pretty intuitive, but I just wanted to make sure that you were aware of that--that each variable is considered separate.2151

So now, if we go ahead and specifically unset the name variable, as well, when we reload this script,2159

it is going to try to output it, and again, we are going to get an error.2166

Now, we are going to get an error saying it can't find the variable name.2170

There are a couple of things we can do to configure sessions in PHP.2176

Some of the more common configuration options that you use are to configure how session cookies work.2180

We know that cookies have an expiration; they have an expires attribute; they also have a domain and a path attribute,2185

which allows you to set the particular name that a cookie is good for2191

and the path that it is good for, as well as how long that cookie is good for.2195

By doing so, for example, if we set the expires...the way you set the expiration date on a session cookie is:2200

you use this session.cookie_lifetime configuration directive, and you can set it to the seconds from when that cookie is created.2210

So, maybe we want our cookie to be deleted in a half hour.2219

That means that, if our client tries to come back to that website and continue that session a half hour later,2222

it is not going to pass that cookie along anymore, because it is going to be expired.2227

Our web server is not going to recognize that, and it is going to maybe output a message that says you don't currently have a session.2230

And then, the other thing we can do is set the domain path for a cookie, if we want to set specific cookies for certain parts of our website.2237

If we go and look at php.ini, in the session section, we can see that there is a cookie_lifetime configuration parameter,2243

which, if it is set to 0, means the cookie expires whenever the browser is closed.2258

It has a cookie_path, which defaults to the root directory of whatever domain it is on.2263

And then, because domain is set to blank, it sets it to whatever domain that cookie is generated for.2267

If we go and view our cookie for this particular session that we had created in our last example,2273

and we look at localhost, we can see that we have a cookie called localhost that has been created.2280

It has a path of just a forward slash, which is the root path.2286

And we can see that the name of the cookie is PHPSESSID, and its content is the unique SID that was generated.2290

What we can do is: we have a script in the example-3 directory...let me just clear cookies...sessionConfig.2303

And this just provides a little bit of output about these configuration directives.2316

It provides information about the two configuration directives we talked about before:2324

save_path, which says that the session files are stored to this directory xampp...2326

It has the session_name directive, which we saw was PHPSESSID; and then, we can see that it has these cookie configuration directives that we just saw the values for: 0, empty, and path.2334

And if we look at this page, it actually calls session_start at the beginning.2348

So, when we view this page, it has started a new session.2351

And if we look down here at our response, we can see that there is a Set-Cookie header that has a new PHP session ID set.2354

Well, if we go and look at this cookie, we can see, again, that it has this unique ID.2365

But its path is set to the regular path, and its host is set to localhost.2376

Well, let's say we want to change that, so that when this script starts a session,2380

it generates a cookie that only works for this particular path.2385

For example, this example-3 directory--we can go to our php.ini file; let's explicitly set the domain to localhost;2389

we'll set the path equal to the path of the directory of this particular example.2400

And let's say we want the cookie to expire in 60 minutes, which would be 60 seconds times 60 minutes--3600; it is going to expire in an hour.2406

We have changed the configuration; so we go ahead, and we are going to restart Apache.2414

If we go ahead and delete the current cookie that we have, and we reload this page, we are going to see a couple things.2422

We are going to see that now our session cookie has a lifetime of one hour.2429

It has a domain explicitly set to localhost, and it has a path set for this example-3 directory.2433

So, this session is only going to work for scripts within this directory.2438

If we look at the Set-Cookie header, we can see that it provides an expires attribute; it provides a path attribute and a domain attribute, as well.2442

Those are things to configure the session cookies.2458

There are also some configuration directives that determine whether PHP should use cookies to manage its sessions,2461

or use a URL parameter, as we had talked about, to pass a session ID between the server...2467

There is a directive called session.use_cookies that says that the server should use cookies2473

to send the session ID to the client, and to expect it back from the client in the form of a cookie.2480

There is another option called session.use_trans_sid, which is saying to use a transparent SID.2486

What that is going to do is: when that is enabled, and cookies is disabled, any time you generate output2493

for your particular script, what PHP is going to do is go through and find any source or href...2499

basically, any links that you have on your page--and it is going to2505

append a query string to them that contains PHPSESSID equal to whatever the session ID is.2508

What that is going to do is: any time a user clicks on those particular links,2515

PHP is going to be able to get that session ID via this GET variable.2518

One other thing that you can do is: there is a configuration directive session.use_only_cookies,2523

which explicitly sets and forces that you can only use cookies for transferring SID's.2526

And that is the safe and secure way to do it.2532

And because of that use_trans_sid configuration directive, managing SID's is strongly discouraged for security reasons.2536

And if we just look at our sessionConfig, we have a section that I have commented out.2548

And it is just going to output some of these configuration directives that we have.2558

We can see that we are using cookies--we are not requiring the use of cookies, but we are also not using this transparent SID.2566

For the homework challenge, what I want you to do is create a couple of pages that are going to make use of sessions.2577

I want you to create an HTML page called login.html that is going to contain two text inputs: one called username and one called password.2584

And then, when you submit that form, I want it to be submitted to a script called welcome.php; and have it use the GET method.2592

What welcome.php is going to do is start a session.2601

And then, it is going to attempt to verify a user's login information.2605

We are going, for this homework example, to consider a user login...if they provide any non-null value for username2610

(so if they provide any text for their username), and if they provide the password (which is the string '1234'),2616

then we are going to say, "OK, this user is verified and can be logged in."2622

If the user is verified, then I want you to create a session variable called username.2626

And remember, to do that, we are going to be using the _SESSION superglobal.2631

And then, set its value equal to the username value that was submitted on the form.2635

If it is not verified, then I want you to just ensure that no username session variable exists.2641

And the way that you are going to do that is with the unset method.2647

On the same page, if the user was valid, I want you to output a message that says the user has been successfully logged in.2652

And include a link to another page that you are going to create, called member.php, which is a special members-only page.2659

And it is going to require that a user be logged in, in order to view that content.2665

If the user is not valid, just output an error message stating that the username and password were incorrect.2669

The way you can test to see if a user is logged in is: you can test to see if the username session variable is set, using the isset method.2675

And so, if the user was able to log in...we saw that, in a previous step of this homework,2685

you are going to go ahead and set a session variable called username;2692

so, if we test if that username variable exists, then that is going to let our script know that the user has been logged in.2694

And so, that is how you are going to tell whether to output an error message or output a message about the members-only page.2700

On the members-only page (member.php is a script you can only view via logged-in users),2706

if a logged-in user tries to view this script, then go ahead and output the user's username they provided on login.html.2712

And so, that is going to give you practice with accessing session data.2719

You are going to have to access that _SESSION superglobal array in order to get that username that was provided.2722

And if a non-logged-in user tries to view the page, just output an error message stating that the user must be logged in to see the page's content.2728

Again, the way you can test if a user is logged in is just to test if this username session variable has been set,2735

because we know that once a user has been validated or verified, that username session variable gets set.2741

Your script should make use of the session_start method, the _SESSION superglobal,2748

and then also this unset method for deleting variables...and actually the isset method, as well,2753

for a construct for testing for the existence of a session variable.2759

That ends today's lesson; thank you for watching look forward to seeing you next time.2763