eCommerce session data persistence - php

I'm currently building a shopping cart for an eCommerce site and am wondering about the best way to persist user data in the session during the checkout process.
The user flow works is as follows:
shopping cart -> login/register -> select delivery address -> confirm -> pay
My issue is once a user is logged in, I want to display a list of their delivery addresses so they can select one. The easiest way to do this is querying the model by the user's id, but my concern is for security - my first thought was to store the user id in the session and then use this to retrieve the addresses. However there's nothing to stop another user potentially hijacking this id (just by guessing random numbers) and revealing addresses for other users. I could perhaps use their email address, but this too could potentially be guessed. Is my best bet to use a combination of the two, or is there a better way?

PHP has built-in session capability. It loads a unique cookie to the browser and allows you to keep all session data on the server-side via the $_SESSION array. The cookie ID is unique for the session, not the user, so it changes each time the user signs in (if the cookie has expired). If you conduct the session in https, it's very secure. Without https, the session is vulnerable to someone with the (special) knowledge and inclination to intercept the cookie data, though such an interception is not easy. Depending on how secure you want to be, running without https may or may not be acceptable for you.
You can read more about PHP session capability here:
http://php.net/manual/en/features.sessions.php

Related

PHP Redis session handler multi user

Lets say we have a user, he logs in and browses the site like usual. Then we have lets say... the brother of this user and he wan'ts to login to the same account from a different ip or a different browser. Is it possible to check if redis has a current active session and deny access for this very reason to prevent multilogin for the same user?
First, what does your question have to do with both php and node.js tags? In which one did you tried to implement your case?
Secondly, whatever the environment might be, what is stored into Redis depends on what you decide to store besides the session data. Usually session data stores a random sessionid and a userid associated to it. Nevertheless, in some cases you can chose to associate a session to a user than has not yet authenticated, therefore storing a session without any user associated to it.
Preventing concurrent user access from different IPs has more to do with the authentication mechanism, rather than session logic.
One approach for preventing concurrent logins from different IP address is to save a map of active users like <userid, ip>. Then after you check the credentials, you also check that map to see if the user is active from a different IP address. In that case you can deny the authentication.
This solution also implies some clean-up mechanism for users that do not safely logout, which is very similar to the session clean-up (time_to_live). To take advance of the existing implementation, you can add an IP address field to the session storage along with the userid at authentication using the same logic for authentication as previously described. The session will now look like <sessionid, userid, ip>. It's just a way to piggyback on the session storage and take advantage of it's clean-up process.

Android to use cookies or sessions?

I am working on an android app that is actually gets user data from android device and then to put it on the server, like to get user name, password, email for registration purpose and then user login to access the app menu (to see list of products, search for products and to add his/her own product details in the list). So using cookies and sessions would be a good idea for my app. Cookies can be blocked by the user and sessions every time to login to access.
But as i am totally new to this concept of cookies and sessions so it would be good to ask a question here before i have to start, that which one should i use cookies or sessions ?
The user can not block cookies. Cookies are simply headers that you will send in each request.
Cookies are easier to handle on the server side. You will simply use $_SESSION["variable"] to get/set any variable for the user. It will simplify your life on the server. However, I think the main drawback will be maintainability and administration of sessions. For example, if a user logs in again on a different device and you want the first session to be invalidated. It is not very straight forward.
If you want to use sessions, you will probably save them in a table on some database. You will need to fetch the session details when you need them. This is sort of extra effort. Yet, database sessions provide some kind of administration capabilities straight away.
I prefer database sessions for what is stated above and some other reasons. However it is up to you

Shopping cart persistence: $_SESSION or browser cookie?

On an e-commerce site with no username/login to persist cart data, would it be better to use the PHP $_SESSION variable or a browser cookie to persist items in the shopping cart? I am leaning toward $_SESSION since cookies can be disabled, but would like to hear thoughts from you.
Thank you in advance for your consideration.
Neither
No large sites would dare store a user's cart in a session or cookie - that data is just to valuable.
What customers are buying, when they select items, how many they purchase, why they don't finish the checkout, etc.. are all very, very important to your business.
Use a database table to store this information and then link it to the user's session. That way you don't lose the information and you can go back and build statistics based on users carts or solve problems with your checkout process.
Log everything you can.
Database Schema
Below is a simplified example of how this might look at the database level.
user {
id
email
}
product {
id
name
price
}
cart {
id
product_id
user_id
quantity
timestamp (when was it created?)
expired (is this cart still active?)
}
You might also want to split the cart table out into more tables so you can track revisions to the cart.
Sessions
Normal PHP Sessions consist of two parts
The data (stored in a file on the server)
A unique identifier given to the user agent (browser)
Therefore, it's not $_SESSION vs $_COOKIE - it's $_SESSION + $_COOKIE = "session". However, there are ways you can modify this by using a single encrypted cookie which contains the data (and therefore you don't need an identifier to find the data). Another common approach is to store the data in memcached or a database instead of the filesystem so that multiple servers can access it.
What #Travesty3 is saying is that you can have two cookies - one for the session, and another that is either a "keep me logged in" cookie (which exists longer than the session cookie), or a copy of the data inside separate cookie.
As pointed out by Xeoncross, it is very important to store any possible information for analysis. So one should not entirely rely on sessions and cookies.
A possible approach is-
Use sessions if not logged in
If the user is not logged in, you can store and retrieve the cart items and wishlist items from session using $_SESSION in PHP
Use database when logged in
If the user is logged in then you can consider one of the two options -
Store the cart item or wishlist item in database alone
Store the cart item or wishlist item in database as well as in session (This will save some of your database queries)
When user logs in
When the user logs in, get all the cart items and wishlist items from the session and store it in the database.
This will make the data persistent even if the user logs out or changes the machine but till the user has not logged in, there is no way to store the information permanently so it will not be persistent.
Getting required data
Whenever you are trying to access cart or wishlist do the following check -
If the user is not logged in then look into session
If the user is logged in, query database if you are storing in the database alone, otherwise you can just look into sessions if you are keeping session updated along with the database
I would store it in a SESSION. My wish list is rather long, and I am afraid that it will not fit in the 4K storage that a COOKIE may occupy. It forces you set the session time out to a longer period.
note: there are some countries (like the Netherlands, where I am) that have very strict policies about cookies, and you may be forced by legislation to use Sessions.
Some points to help:
Cookies:
info is persisted untill the cookie expires (what can be configured by you);
tend to slow down the communication between server and client, since it has to be exchanged between the two in every request/response;
its an insecure form of storing data and easy to sniff;
they also have a limit to store data.
Session:
all information is persisted in the server, thus not been exchanged with the client.
because it is not shared across the network, its a bit more secure;
all info is lost when the session ends;
If you are hosting in a shared host, you may have problems with session ending in the middle of a operation due to a push on the resources by any of the sites hosted on the same server.
I would personally go with sessions, since I'm assuming to be a small/meddium auddience page. If it grows, you would be better with a simple DB structure to store this data, with a maintenance plan to get ridge of unnecessary data (eg: clients that choose some products but don't do the checkout).
You might consider using both.
The drawback with $_SESSION is that the session is cleared when the browser is closed.
Use sessions, but attempt to populate the $_SESSION data from a cookie, if it's available.
I would use a session. If a user has cookies disabled then the session won't be able to start as the session ID is stored on the user's machine in a cookie.
There are some settings you may want to look at in order to attempt to keep the sessions for longer.
Prevent the session cookie from being deleted when the user closes their browser by running session_set_cookie_params() with the lifetime parameter set. This function needs to run before session_start()
You may also want to extend how often sessions are cleared from the server by modifying the session garbage collection settings session.gc_probability, session.gc_divisor, session.gc_maxlifetime either in php.ini or using ini_set()
If you have other websites running on the server and you modify the above garbage collection settings you will need them set in php.ini so they apply to all websites, or if you are using ini_set() then you might also look at saving these sessions to a different directory than other websites by modifying session_save_path(). Again this is run before session_start(). This will prevent the garbage collection of other websites clearing up your extended sessions for one particular site.
I would also recommend setting the following session settings in php.ini session.entropy_file = /dev/urandom, session.entropy_length = 256, session.hash_function = sha512. That should give you a cryptographically strong session ID with an extremely tiny chance of collisions.
And make sure you have an SSL cert on your site to prevent man in the middle attacks against your session ID.
Obviously a user could still decide to manually clear all their cookies which will take the session ID cookie with it but that's a risk I'd be prepared to take. If I was halfway through a shopping cart system and hadn't checked out, I wouldn't go and clear my cookies. I still think sessions are better than just using plain cookies.
The data is secure enough so long as you are the only website that has access to your sessions directory and your session ID is strong. And by extending the server's session storage time your data can persist on the server.
There are further measures you could employ to make your sessions even stronger. Regenerate your session ID every 20 minutes, copying the data over. Also record session IDs against IP addresses in a database and check to see if a particular IP address attempts to send more than X number of session IDs in a given time to prevent someone trying to brute force a session ID.
You could also store the data in a database linked by the session ID, instead of in a session file on the server. However this is still reliant on a session ID which is stored in a cookie and could disappear at any time. The only way to truly be sure that a user doesn't lose their cart is by having them login first and storing in a database.

How to make an authenticated user persist using a cookie

I am making a registration/login system with php. I think I have all the initial login stuff worked out(hashing password with salt, store in db...).
My question is in regard to keeping a user logged in between pages after their initial login. The way I understand it is that one method is to have a table of sessions on your server that stores a random unique id for each user and to store that id in a cookie on the user's computer. This way for each page they load all you do is lookup their session id in your database.
What I don't understand is how is that is secure? Couldn't somebody just sniff the ID and then fake being that user. Someone could even just try guess IDs.
I also read that it is better if the ID changes on each page visit. How does this increase security? It seems it just would decrease the amount of time any ID could be used.
Also how would any of this change with a "Remember Me" feature that would be stored for long time?
The ID you are describing is precisely what the session ID is, except it's handled for you transparently by php (browsers pass along this session ID with the cookie).
The security flaw you are describing is precisely what firesheep takes advantage of. You can prevent the session ID from being sniffed by making sure that all authenticated requests to your site take place over ssl. This not only includes logging in, it also includes any time an authenticated user tries to access a page (which means the browser will be passing along an authenticated session id).
If a user tries to access a page not via SSL, you should ideally redirect them to an SSL page and give them a new session ID, because the old one could have been compromised.
The key to such a system is that you don't randomly generate the key--you generate it using facts about the user, ones that another client wouldn't have knowledge of--like the user's IP address, user-agent, and session id. Then you make the user authenticate using that key and their session id (which is transparently handled by PHP).

When setting users' preferences, is it best to use cookies as to session? (PHP)

For each user, I want to allow them to choose their preferences, such as which categories to show on their profile, which tags they want to see, etc. Would cookies be better than sessions because they don't expire when users logoff?
I think the best solution is to mix cookies and database - the last one for logged in users.
Cookies are fine, because the user doesn't have to log in on your website to have some preferences saved.
But if somebody will login to your page than you got ability to save his preferences in more stable source - server database. Then these preferences are available from every computer and won't disappear after "browser cleaning".
EDIT:
Don't use sessions - they are worse than both, cookies-based and database-based solution.
Why sessions aren't a good idea? First of all they rely on cookies (session id which required for proper work of sessions system is stored in cookie called SID/SESSID/SESSIONID (in most cases)) so whenever you clean cookies you also lose your session. Moreover session are available only for few minutes (from first page load to browser close or about 20 minutes of inactivity on website) while cookies may be available for few months or even years!
So how should you do that?
There are two scenarios:
When user is not logged in:
Then when he change some preference store it just in cookie
When user is logged in:
Then when he change some preference just save it in database:
INSERT INTO preference (user_id, key, value) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE value = ?;
That's example for MySQL but you can do this the same in others RDBMS.
And how do you get final preferences?
// That's VERY unsafe code... you HAVE TO do necessary validation (this is only an example)
$preferences = unserialize($_COOKIES['preferences']);
if (/* user is logged in */) {
$databasesPreferences = result_of_query('SELECT key, value FROM preference WHERE user_id = ?');
$preferences = array_merge($preferences, $databasesPreferences);
}
Sumary
This solution gives you the most stable way for handling user preferences for both logged-in and non-logged-in users.
Cookies can have an expiration date. If there is no sensitive data in them then they're fine to use, however if you're storing thing like user id's, etc. that will be used in queries you're best off using sessions as they're stored on the server where people can't manually get at them.
You generally have three choices of where to save user preferences:
database
cookies
session
When deciding between these, each solution offers different behaviors in terms of:
persistence
locality (tied to a browser or account)
security
If you need longer-term persistence of these value, you should put them in the database. If you want them to not require a sign in, then cookies are a better choice. There really is no one right answer-- it depends on what you're trying to accomplish.
What is the point of using cookies when the user has logged off??? User needs to be using the website in order to read from the cookie and apply the settings. Once the user has logged in, you may query the database and store the options in sessions until the user has logged off.
My recommendation is that it's best that you use sessions as they are much safer.
Cookies are nice because they can last between visits or "sessions". However they are also user editable and readable globally. Storing sensitive data like a login, password, session id, etc can lead to a malicious site hijacking the session or users information. Also a crafty user could alter the cookie to change the privilege level or user who is logged in and impersonate them.
Sessions are very secure because they are stored server side away from the prying eyes of users and other web sites. They do have the limitation that anything that's stored in them disappears once the session ends.
When I do login systems I prefer to use a sessions. You can pull the user from the database and then load various user defined settings into the session.

Categories