Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Is it necessary to end a session?

I am developing a website. I am using php for the server side language. I am currently working on my sessions.php file. Do I need to program in session_unset & session_destroy? Or will the compiler do this for me?

As of now, here is what my code looks like:

<?php 
// start the session
session_start();
?>

2 Answers

Andrew McCormick
Andrew McCormick
17,730 Points

I could be corrected, but I don't believe you have to. The unless you specify otherwise, a users session will terminate when they close their browser window.

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

If you need to logout user, you need to call function, which will destoying user session using unset($_SESSION); or session_destroy(). Session will exist until time as you delete it. Even if user close a browser, PHPSESSID still stored in your cookies. So if you want to destroy session, you need to do it on server-side, PHP interpreter will not delete nothing for you, if you will not command him to do that.

Also, if you carry about security of your API, you can use JWT and OAuth instead of session usage. For example, you can read more here

I thought that sessions and cookies were two different methods for creating a 'session'. Can you clear up this confustion for me?

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

Each time you start a session, PHP check if you send cookie with name PHPSESSID. If your broswer didn't send it, PHP will create new cookie with unique PHPSESSID on your computer and will connect with your session. So, PHP just need to know your personality and which session PHP should give you back. It will send to server each time you request some resource:

PHPSESSID in Browser storage

PHPSESSID in HTTP request

You can redefine this variable name in php configuration file, or in your application, so for example, if you will use slim, session cookie will be named as slim_session. The most vulnerable place here, that if someone finds out your PHPSESSID, he will gets access to your session. That's why I am suggestion you to learn OAuth and implement in your app.