Setting Cookies With PHP

I am currently adding a shopping cart to a CMS script that I have written. The object is to eventually have a script that many people will find useful on their sites by allowing them to generate traffic from their articles as well as from their shop. In this post, I will discuss some of the code used to make the cart work, how it works, and how I will implement the code into my own script, which again is available for free download at The Collard.

One of the first things that I needed to do was create sessions. This will allow my users to create a unique session and only allow the products added to their cart during the visit from their machine. In the previous versions of the collard, their was no session variables defined so I set this up by editing the functions.php file of this script. If you are not using this script, you will need to create a functions.php page and add this function to that page.

<?php
function Session()
{
//This will generate an encrypted string and will set the cookie. It will also be used in the cookieId field in the
//cart
if(isset($_COOKIE["cartid"]))
{
return $_COOKIE["cartId"];
}
else
{
//No cookie was found. We will set the cookie and return the session ID
session_start();
setcookie("cartId",session_id(),time()+((3600*24)*30);
return session_id;
}
}
?>

This code has now created session ids and will return to that session id if visited again within the next 30 days. This allows the user to add products to a cart and if they decide to think about it, need to wait until payday, etc., the products are now in the shopping cart and will be available to them when they come back to complete the purchase.

Now to explain how I did this. I used the setcookie function to create the cookie on their machine. In order for this cookie to work for the next 30 days, I defined that by adding the time function to the string. There are 3600 seconds in every hour (60*60). I multiply that by 24 hours in a day and then by 30 days in a month. That sets the cookie to last exactly 30 days from the moment it was created.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>