Osirion System Technologies Header Split Image
  site search:    
   
Osirion System Technologies Header Split Image

reliable & affordable solutions

Our solutions will not only astound you in their reliability, but their affordability as well. Whether you are looking for web hosting, web design or search engine optimisation or any other of our services - you wont be disappointed! No matter which of our solutions you require, you will see this statement will fit all areas of our expertise.
 
 


 
 
 


 
 
 


 
 
We Accept:


articles

Make Your Own Custom PHP Shopping Cart


2008-02-18

So you've got a client and/or a web development project that requires stitching different scripts and functionality together into something cohesive. In almost every web development project out there, many, if not all the components have been created in the past and the source code made available. In PHP, one such common place thing is a check out process to purchase products online. Sometimes using a pre-developed open source solution is ideal, but there are occasions when developing your own code is optimal or even required. Whether it boils down to your customer preferring a custom solution or if none of the open source projects meet your requirements, there are many reasons why you may choose to custom code a shopping cart. In this tutorial we'll explore a bare bones PHP cart that can easily be adapted and integrated into any type of web development project.

To start out, it should be noted that making a shopping cart system is actually quite trivial with an intermediate knowledge of PHP. I've written this tutorial by deconstructing a more complex shopping cart I wrote for an e-commerce script that I authored. All accompanying code is licensed under the MIT license. The full source code of all the examples can be download here.

First, we'll break down the problem into smaller chunks so we know the best way to approach the situation. Now, there's 3 main parts we'll be dealing with, 1) adding products to the cart 2) removing and managing cart items 3) keeping and storing the data. Obviously to make something functional, we're going to need two more ingredients: products and a payment method. We won't go too in depth into either of those as both warrant detailed tutorials of their own.

So now that we know the basic elements that will make up our code, let's look for and decide on some solutions to address each task. First, adding a product to the cart can easily be accomplished using PHP's session management functions to store the carts content and keep track of individual users. To start a session in PHP, you simply start the session using the session_start() function. We'll get into that in just a bit. Of course, adding a product is hard to do without having any products, so we'll also need to make a few example products so that we can add and subtract them. Let's do that now, in a new file we'll call product.inc.php

<?php

$product[0]['number'] = 0;
$product[0]['name'] = 'Gold Watch';
$product[0]['price'] = '$129.99';

$product[1]['number'] = 1;
$product[1]['name'] = 'Silver Watch';
$product[1]['price'] = '$89.99';

$product[2]['number'] = 2;
$product[2]['name'] = 'Bronze Watch';
$product[2]['price'] = '$24.99';

?>

Now, what we've done in this code is added 3 products, each one with 3 attributes: name, price, and shipping. This system will work, but a more robust system would be one built through a database. We'll leave that to you to implement however, as our main goal is not the products, but the cart system itself.

Since we have the products, we'll next need to build a simple product page that will allow us to view the products and choose the appropriate items to add to the cart. Again, this is more of a demo page that illustrates the key points. We'll call this file index.php and use this code:

<?php require_once('product.inc.php');?>
<html>
<head>
<title>Your Store</title>
</head>
<body>
<?php
foreach($product as $productDetail) {
echo '<h1>'.$productDetail['name'].'</h1>';
echo 'Price: '.$productDetail['price'].'<br />';
echo '<a href="addtocart.php?item='.$productDetail['number'].'">Add to cart ></a><p />';
}
?>
All done, then <a href="checkout.php">checkout!</a><p />
</body>
</html>

Now you'll see in this code that we include our first file, product.inc.php, using PHP's require_once function, you can skip to the next paragraph if you're already familiar with it. By using this instead of include, or require, using require_once we're telling PHP to halt execution if the file cannot be included (this is the require part) and if it's already included, do not include it a second time (this is specifed with the _once aspect of the function name.)

Next we do a basic HTML head, before we get to our next PHP code. The foreach statement iterates through each array. This advances the array pointer one level deeper into the array, using $productDetail as the current iteration. For example, inside this foreach statement we can echo $productDetail['name'] to display the current products name. This is exactly what we did in our foreach loop, which will echo out every new item you add to product.inc.php. Notice within this loop that we've made a link to viewcart.php and are sending the GET variable named item over to it. This value is equal to our product number defined in product.inc.php.

Finally in the source, we'll have a link to checkout.php so that users can finish up the process and actually buy our product. We'll include this link in viewcart.php as well so that they can proceed to check out as well.

So now we have three more files to make, addtocart.php, viewcart.php and checkout.php. Additionally, remember that viewcart.php needs to know the item number to add to the cart, which is sent through the item variable.

Let's code addtocart.php now:

<?php

require_once('product.inc.php');
session_start();

// If the item number is numeric, let's use it, if not, let's exit the script
if(is_numeric($_GET['item'])===true) {
$item = $_GET['item'];
} else {
exit;
}

$_SESSION['cart'][] = array(
"product_key" => $item,
"prodname" => $product[$item]['name'],
"price" => $product[$item]['price']
);

echo '<script type="text/javascript"><!--
window.location = "viewcart.php"
//--></script>';

?>

Okay, quite a big chunk of code, so let me explain each block. First of all we require product.inc.php to be included. The next line initializes PHP session management, which is where we'll store the contents of our cart. After that, we're going to use the is_numeric() function to insure that the data the user is submitting is formated correctly. If it's not, then the script exits.

After that block of code, the next chunk begins with a call to $_SESSION. We need to add the item to the shopping cart, and this block of code does that by declaring a new array. You'll notice that the second brace on $_SESSION['cart'][] is blank. That tells PHP to iterate from 0, so each additional time this is called, the number will increase. This is the reason why we needed two foreach statements in the last block of code. Notice that when we set the array, we're using the $item variable to select the correct product from product.inc.php

Finally, the last thing this file does is echo a javascript command that forwards the user to viewcart.php. Let's start working on viewcart.php now:

<?php
session_start();
error_reporting(0);

if ($_SESSION['cart']!=NULL) {
foreach($_SESSION['cart'] as $cartItems) {
echo '<strong>'.$cartItems['prodname'].'</strong><br />';
echo 'Price: '.$cartItems['price'] .'<br />';
echo '<a href="removefromcart.php?prod='.$cartItems['product_key'].'">Remove</a> from cart<br /><p />';
}
echo 'All done, then <a href="checkout.php">checkout!</a><p />';
} else {
echo 'Cart empty';
}

?>

Here we first check if theres any data in $_SESSION['cart'], and if there is, we then iterate through each item in the cart using another foreach statement. Towards the end of this statement we introduce another file with a link to removefromcart.php. Note that we pass the product ID through the GET variable prod in order to determine which item to remove from the cart. Let's take a look at removefromcart.php now:

<?php
session_start();
error_reporting(0);

 

$prod = $_GET['prod'];
if ($_SESSION['cart']!=NULL) {
$icounter = 0; $maxcounter = 999;
while ($icounter < $maxcounter) {
if ($_SESSION['cart'][$icounter]['product_key']==$prod) {
unset($_SESSION['cart'][$icounter]['product_key']);
unset($_SESSION['cart'][$icounter]['prodname']);
unset($_SESSION['cart'][$icounter]["price"]);
unset($_SESSION['cart'][$icounter]);
} else {
echo 'No match.';
}
$icounter++;
}
} else {
echo 'Cart empty.';
}

echo '<script type="text/javascript">
<!--
window.location = "./viewcart.php"
//-->
</script>';

?>

This tutorial covers a basic shopping cart web development project. Of course, the next step in this system would be integrating a payment processor such as PayPal. This is what checkout.php is for. You'll simply pull the session variables and pass them to your payment processor. The details of this are specific to each payment processor, and so for the nature of building an ultra portable shopping system, we'll leave that for another day.





View other articles in the Web Development category.
View other articles in the PHP sub-category.
Copyright © 2002-2024 Osirion System Technologies. All Rights Reserved.
Privacy Policy | Terms & Conditions | Terms Of Service | Sitemap