[nycphp-talk] preventing randomized session variable from changing when page is refreshed
bzcoder
bzcoder at bzcode.com
Thu Aug 21 09:38:37 EDT 2008
Kristina Anderson wrote:
> Yes, but if I do $_SESSION['cart_id'], it is effectively the same
> thing, I'm using this random string as an identifier for the unique
> cart. This is effectively the same as $_SESSION['session_id'] -- only
> the name is different.
No, it is not effectively the same.
First off, by doing $_SESSION['cart_id'] instead of manually generating
your own session id, you get the power of PHP working for you in that it
has already done all the things are are attempting to code manually
built right into that session_start() command.
In your examples, you could use the following on every page:
-----
session_start();
if (!isset($_SESSION['cart_id']))
{
session_regenerate_id();
$rand=rand(1,9);
$cartid=$rand.substr(md5($REMOTE_ADDR), 0, 11+$rand);
$cart_id.=substr(md5(rand(1,1000000)), rand(1,32-$rand), 21-$rand);
$_SESSION['cart_id'] = $cart_id;
}
----
This will generate a new id for every person coming into your site, and
give them a cart id.
Secondly, you can regenerate that session id anytime you want and not
lose the cart. So if your collecting a credit card at some point in
your process, someone can't do something like:
Buy this cool book at
http://www.yoursite.com/displayitem.php?itemid=xyz&PHPSESSID=abc
Thus forcing the session id to be set to abc, and then monitoring the
verification page of the checkout process to grab that persons personal
details once they are entered.
Instead, when someone enters the checkout process place the following
bit of code at the top:
----
session_start();
session_regenerate_id();
----
This means that even if someone did manage to fixate the session for
that person, as soon as you begin the checkout process you generate a
new session id for them.
And the cool part is $_SESSION['cart_id'] will be copied along from the
old session id to the new session id without you having to do anything
at all.
All of the above code suggestions are merely a band aid to fix your
original stated goal with minimum amount of code. This requires making
a few lines of change to the top of most of your PHP scripts, and
changing any refferences to the session id to the cart id. This should
not be taken as an endorsement that this is the best way to program the
overall goals, just that it solves this itty bitty problem.
More information about the talk
mailing list