I'd like to know if there is any way to create session data that expires earlier than default session expire time in codeigniter?
For example, storing shopping cart indefinitely but everything else expires after 30 minutes.
Do I have to do it the hard way (deleting them manually)?
Thanks.
My opinion is that you have to use things the way they are designed. Sessions are meant to be a temporary storage as the user switches pages. If you want to store something indefinitely, store it in a database. Thats what databases are designed fore.
To identify the user, and his shopping card, you have to store a cookie with a ID on the users machine, or let the user login or register.
By using a database, and a login mechanism, the user can retrieve his shopping card also on an other location on a different machine.
Let the user delete his own shopping card, and use a cleanup mechanism for shopping cards older then a certain time (3 months, a year?)
The user's cart is usually best kept on the user's machine. Assuming a modern browser, you can use HTML5's localStorage to keep the cart data on the user (since it's not sensitive data, it's fine).
If you are supporting older browsers, you'll need to resort to cookies, but it's still not the server's job to remember which cart each user has.
Related
i have start to creating online store from scratch with PHP and everything is right but i need to know which way is better and safer for creating shopping cart(Basket)
1- work with session? ex: create session['cart'] and save products
2- work with database? ex: create a basket table and save products and after checkout delete everything from this basket
or maybe there is another way more better and simpler that i don't know
sorry for asking this question but i can't find good resource in internet,
thanks for yours Suggests
There are in fact three options:
Cookies
Sessions
Database
Cookies are unsafe. If you save personal data in cookies, malware can easily read that data. You don't want to get your user in that kind of position.
Sessions tend to get deleted when a browser closes - even when it's accidentally. Safety is reasonable. Sessions use cookies to identify an user. A third user can copy that cookie and pretend to be that user.
The database seems to be the best bet so far, but how do you link a database record to a user?
My best bet is to have a database record linked to several (temporarily) constants. If you save IP address and a hash, which saved in a cookie too, you can identify a user even after his browser closes.
The cart will endure until you delete it, the cookie expires or the user changes IP.
Well, where you store the items which a user is going to purchase is completely irrelevant.
I would recommend you stored them in cookies, so he user doesn't need a login to store his basket.
Unless you dont wan't hackers to spy on which product a user buys there is no need for encryption in this part.
But if you want to handle creditcards, you will need to create a https connection.
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.
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
I am in the process of making a website that involves a shopping cart.
There are two major requirements:
The user experience guys want login/authentication to be the very last step in the entire work flow. The user gets to do all the shopping and is asked to login only at the time of checking out.
The shopping cart shouldn't expire(not even on browser close) unless the user (registered or not) does check-out.
In the above context, I have the following question with respect to maintaining the cart's state:
Should I go with file based or database sessions? Please keep in mind this would be for unregistered users. My apprehension is that I'll end up having lots of records in the database.
Another option seems to be to put the cart contents in an encrypted cookie, but then there's a size limitation on the cookie file.
What would you do in this case ? I would really appreciate your answers.
Tracking a user. Use a GUID
encoded into a cookie with an
nYear expiry.
Storing a Shopping Bag. You don't want to store the bag in the cookie, mainly due its possible size. This leaves the option of persiting it to a medium and retrieving it from the medium. Using anything except a database for this would be like going back in time, databases excel at storing and retrieving data.
Managing you Shopping Bag. Now, the
question of your schema, firstly, if
your going to be running queries
against the shopping bags in the
database (i.e. how many shopping
bags contain item x) you probably
want a traditional relational
schema. However this has overheads
in terms of inserting. updating,
selecting (and joining) and deleting
bag data (at some point you'll have
bags that will never be used again
but are taking up precious disk
space). With a busy site, this is a
fair few Traranactions Per Second,
but any database should be able to
cope. If you don't need to query
the shopping bags in the database,
then you can store it as XML. Just
serialize the bag and dump it into a
table, with the PK as the GUID as
stored in the users cookie. This
would be a lot faster than a
traditional schema, plus you could
always tear apart the XML in the
future if a requirment did come up
for a relational schema.
This is what we do (Xml Bag), and we have a million+ customer base.
I would go with database managed sessions over file managed sessions. Make sure you have a session timestamp so that you can eventually kill old sessions (if it's been 12 months, the shopper is possibly not coming back for the items originally in the cart).
Doing this with a database instead of files will make it easier to eventually expire the very-old information.
Note that the database session will only ever be valid as long as the cookie it's tied to on the user's computer. If the user comes back to the store from a different browser, they will not find their session. If two people are sharing the same computer, they will find each other's session. Hopefully no potentially embarrassing items will be in the cart...
Store in cookies the AnonymousSessionID, with which you associate a shopping cart in the database.
Then you'll have a scheduler task to erase anonymous sessions after some time (say, a day). This will keep your database clean of abandoned sessions.
If a user registers, you reassociate their shopping cart with their account permanently. If the users makes an order, you empty their shopping cart.
If you're using ASP.NET here's what I'm (about) to do:
use a Profile to capture the users email as soon as possible (to email them if they dont complete the order). you can enable anonymous profile properties that are persisted to the aspnet database even if the user hasnt actually truly registered.
stick an XML bag representing an order into session. This is persisted in the database with a regular identity ID.
store the ID of the cart in the ASP.NET Profile. that way when the session expires you can just reload it from the ID in the profile. this has the benefit that the user never sees the cart ID in a cookie and you can easily link records between the membership/profile database and the store you're using for your orders
(dont try to store the XML order in the Profile. i think thats asking for performance issues. but in theory you could i suppose)
With those specs I would go with a database based session state. But you should do some heavy reading on how session state is handled in your web server of choice. Since you want to be able to revive the state to the correct person.
I think you have some expectations to manage, or maybe you weren't clear on requirements.
The user experience guys want login/authentication to be the very
last step in the entire work flow. The
user gets to do all the shopping and
is asked to login only at the time of
checking out.
The shopping cart shouldn't expire(not even on browser close)
unless the user (registered or not)
does check-out.
Specifically, an anonymous, not logged-in user's cart being saved? That's madness. Ensure that's not an expectation and clarify it in your design documents.
I am building a website in which the user can select what list items they see in their navigation menu, my idea is to store the menu items that the user selects in a cookie as this will stop the need for the user to be registered member on the website, is it possible to store realtime data in a cookie and how would I do this? For more information the navigation options are built from a mysql result, the then clicks a link and that link is added to a different list, if they click it again it is deleted, I need to add/remove these items from the cookie as the user add/removes it from there list.
i would use the cookie only to identify the user and do all of your menu option saving in MySql.
Grab the user id from the cookie and query the db for the menu_options and display them.
Either way, storing the data in a cookie or in the database, when the cookie expires, so does (effectively) the user. Plus people delete cookies all the time using cleaners like Adware and CCleaner. I do this about once a week. Cookie = Gone.
This is a bad idea.
The number of cookies a browser can store is not defined (however there is a hard limit for most browsers). RFC 2109 suggests at least 20 cookies per host and a min cookie size of 4k. Certainly the latter is adhered to by most browsers.
You're also going to have to replicate all the features of session management without the nicety of having server-side state. You do not want the kind of pain going down this route will cause you. Keep your session data server-side.
There is no requirement for a user to 'log-in' to have a session. You just need to assign them an automatic identity in a persistent cookie (the replace that if they ever do sign in). And map the session back to a more long term storage when the user changes the config.
C.