php refresh to set cookie

Associate
Joined
19 Jul 2006
Posts
1,847
My cookie shoping cart app is slowly getting there. but im having a problem with the cookies not been set untill the page is refreshed so the displayed basket is always 1 item behind.

im thinking of using
PHP:
<?
    
            header("location:" . $_SERVER['PHP_SELF']);
    
?>

But i only want this to do it once, just so the cookie is set properly.
 
If by 'cookie shopping cart' you mean something that's entirely in cookies and doesn't have a database at the back end of it... ignore the next paragraph

(It's probably a much better idea to just store a 'session' cookie and tie that to the contents of their basket which you store server-side. Now back to your current method assuming you're hard-and-fast set on it...)

You have to watch for creating infinite redirects with this sort of method. It might be an idea to look into doing it like this:

1. first request comes in to your server for cart.php and no cookies are passed to your script, so you send back some default cookie (just one that means 'the cart is active' essentially) along with some javascript in your html
2. once the page is loaded your javascript can check for the presence of the cookie, and if it's not there, redirect the user to a 'sorry you need cookies enabled, stop being a paranoid retard' error message page
3. a subsequent request comes in to add an item to the basket, along with the current contents of the basket, and after you set the item in the $_COOKIES array, you just use this array to print the basket contents in the html aswell. Or if you're using setcookie() you also take what came in from $_COOKIES into a temporary array and append the new item onto it. I don't know how this would ever cause you any trouble, there's no reason why anything should 'lag' one request behind anything else
 
Last edited:
Back
Top Bottom