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

Ben Attenborough
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ben Attenborough
Front End Web Development Techdegree Graduate 32,769 Points

Persistent data across pages

I'm trying to implement a log in page where users can log in with their details and for their user ID to persist across all the pages of the site (so that the site can show data relevant to the user - for example their blog posts). I could do this with cookies, although some users turn cookies off. I have also done some research and discovered session storage which stores data persistently using Window.sessionStorage (I may have this wrong, see https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API).

My question is, is using session storage and cookies enough of a fallback or do I need another way to persist the user id data (such as this complicated method http://www.troubleshooters.com/codecorn/php/persist.htm). The page just mentioned is very old so I presume there are now easier ways to persist data securely (using the get method would not be very secure - see the troubleshooter page).

5 Answers

First you have to start the session - this would be at the very beginning on the script.

You can jump into the session very easily with:

<?php

$_SESSION;

just like you access $_POST or $_GET. When your user submits the login form and they are 'logged in', you could do something like

<?php

$_SESSION['user']['id'] = $id;

and you'll be able to access that ID in future by:

<?php

$_SESSION['user']['id']

This is a very basic example of how to use a session to grab out your logged in user

When you start a session, you need to call the session_start(); function, not using $_SESSION; which means nothing.

EDIT: I was incorrect on this second part.

Ah gotcha ;) I thought I mentioned session start!

I admit, it is my personal preference to apply multidimensional arrays to the session because:

<?php

$_SESSION['user']['id']
$_SESSION['user']['name']
$_SESSION['user']['address']['line1']

$_SESSION['cart']['id']
$_SESSION['cart']['businessID']

//etc

feels slightly more object orientated than

<?php

$_SESSION['userID']

So it's more than possible. I'm yet to find somewhere where this is discouraged, but maybe you can pass some knowledge along!

As a side note $_POST can also contain multidimensional arrays i.e. if you were to have form inputs with names like:

<input type="text" name="address['line1']">
<input type="text" name="address['line2']">
<input type="text" name="address['town']">

and so on

No, you are correct. It seems that we both made mistakes! lol I went ahead and edited my comment so that no one will get confused. Apologies!

Session variables will only last so long as the session is open with the server. By default, the session is closed whenever a user closes their browser window. Cookies can be set to expire after any length of time you choose, but since they are stored on the end user's computer, they can be deleted at a moment's notice and often are. If you only want the data to be persistent for a short while, then you can use session variables or cookies.

But if you need permanent storage, you'd want to go with a database and SQL or something similar so that you can retrieve the data regardless of what's going on with the end user's system because the database will be stored on the server, of course.

Ben Attenborough
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ben Attenborough
Front End Web Development Techdegree Graduate 32,769 Points

I'm not particularly worried about data persisting once the browser is closed. But I do need the user's ID to persist across new pages. And obviously as this ID will give the user access to their account this ID needs to be secure and I need to prevent other people using it to access accounts that are not theirs

If you're going to have users log in, you need to be worried about data persisting after the browser is closed, especially the user's data that they use to log in. This means you need to use, at the very least, some sort of database so that you can retrieve/set data combined with an SSL certificate so that you can keep the user's sensitive data secure. You can then use session variables to retrieve data from the database and then use that to authenticate the user whenever they do anything that involves a modification of their own data or the data they post.

You should do some research on MySQL injection prevention, session hijacking prevention, and other user authentication security methods.

Ben Attenborough
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ben Attenborough
Front End Web Development Techdegree Graduate 32,769 Points

@Marcus. Sorry, I should have explained that I am using a database but I needed a method to persist the user id data so that the user can switch pages whilst still being logged. I think using a PHP session will do what I want, however as you have suggested session hijacking and sql injections are something to worry about.

I thinking I am going to build this out in order to learn more about how to do these things and to help me research the subject. But perhaps for the actual project I'm working on I might use WordPress instead?

@Tom thanks for that information I'll look into that

Session variables will definitely allow you to do that. In any case, best of luck to you, Ben! I hope your project is a smashing success :)

If you're using PDO to interact with your database (please tell me you're using PDO!) then you shouldn't have to worry too much about sql injection - the object handles this pretty well.

re: session hijacking - I would suggest considering how secure your application really needs to be before going down a long road of internet security, but I agree more of a problem.

Applications frameworks (I know Laravel does) have built in functionality to handle a lot of the security stuff that's been mentioned. If you're up for it, dive into the Wordpress or Laravel codebase to see if you can find out how they do it ;) If it was me I would have a play with sessions locally then migrate to a framework as you suggested :-)

Hope this helps

I just found this thread, as I was looking for information about PHP sessions. I am also working on a project that involves users logging in, editing their profile, and so on. I remember watching a video or two that touched on PDO but I'd like to get more familiar with it. So, I will try digging through some of the tracks to see what I can find.

Just in case I don't find what I need, would any of you be able to provide tracks (or other sites) containing good information about sessions and/or PDO? Thanks in advance for any help you can offer!

Ben Attenborough
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ben Attenborough
Front End Web Development Techdegree Graduate 32,769 Points

eddie I don't know your level of experience so sorry if some of the following is already known to you, however:

If you haven't already considered it perhaps you should also look at using WordPress (or Joomla or Drupla) as a CMS as they will handle the fiddly bits of managing users securely. There is a series of videos on WordPress that I can recommend.

If you want to learn how to do it by hand (which is worth it for the educational experience alone - plus it gives you more flexibility) then I would recommend mastering mySQL first. Then set up a simple database to hold usernames and passwords and get that to work. Extend this by storing data in the db and associating it with a specific user - so only that user can access it. After that you can look at implementing user sessions to log in users and keep them logged in between pages.

Finally and most importantly, if you are making a real project you will need to have some security. You will need to hash the user passwords so they cannot be hacked. It isn't the easiest thing to do but it is possible with some patience. Let me know where to begin and I can link to some websites and tracks on Treehouse to help.

Hope that helps, and good luck!

Ben, thank you for responding.

You're right. I would like to code everything myself so that I know exactly what's going on behind the scenes. I'm familiar enough with MySQL and PHP that I have already created a database to hold user data, and a working log-in page (it matches up the name and password correctly). However, I have never worked with sessions before.

My site is nothing major. The only real piece of sensitive information anyone will have stored on the database is their password. No SS#, CC#, or anything like that will ever be used. Sure, I'd like to make it as hackproof as possible but it's something I can worry about after everything is up and running.

Ben Attenborough
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ben Attenborough
Front End Web Development Techdegree Graduate 32,769 Points

Cool, thanks so much for this, both of you. Yes Tom I AM using PDO ;) I've been learning WordPress but in many ways it seems more effort than just hand coding the thing myself. Plus building out a log in system is teaching me a lot about how these things work. However for the main project I may go down the WordPress route as it'll give the client more control over adding pages and maintaining the site. This is just a charity project that I'm doing as a volunteer.