A Shopping Cart using PHP Sessions

This posts illustrates a relatively simple shopping cart using PHP sessions to store cart details, quantities and total cart amount.  The cart has an add to cart button , remove from cart button and displays the total value of the cart.

This post is taken from part of the book PHP Tutorials: Programming with PHP and MySQL which is available as a paper back printed version or as a downloadable Kindle version. Click here for paper back version.

The following listing is the complete PHP shopping cart:

<?php session_start();
#cart.php - A simple shopping cart with add to cart, and remove links
 //---------------------------
 //initialise sessions

//Define the products and cost
$products = array("product A", "product B", "product C");
$amounts = array("19.99", "10.99", "2.99");

 if ( !isset($_SESSION["total"]) ) {

   $_SESSION["total"] = 0;
   for ($i=0; $i< count($products); $i++) {
    $_SESSION["qty"][$i] = 0;
   $_SESSION["amounts"][$i] = 0;
  }
 }

 //---------------------------
 //Reset
 if ( isset($_GET['reset']) )
 {
 if ($_GET["reset"] == 'true')
   {
   unset($_SESSION["qty"]); //The quantity for each product
   unset($_SESSION["amounts"]); //The amount from each product
   unset($_SESSION["total"]); //The total cost
   unset($_SESSION["cart"]); //Which item has been chosen
   }
 }

 //---------------------------
 //Add
 if ( isset($_GET["add"]) )
   {
   $i = $_GET["add"];
   $qty = $_SESSION["qty"][$i] + 1;
   $_SESSION["amounts"][$i] = $amounts[$i] * $qty;
   $_SESSION["cart"][$i] = $i;
   $_SESSION["qty"][$i] = $qty;
 }

  //---------------------------
  //Delete
  if ( isset($_GET["delete"]) )
   {
   $i = $_GET["delete"];
   $qty = $_SESSION["qty"][$i];
   $qty--;
   $_SESSION["qty"][$i] = $qty;
   //remove item if quantity is zero
   if ($qty == 0) {
    $_SESSION["amounts"][$i] = 0;
    unset($_SESSION["cart"][$i]);
  }
 else
  {
   $_SESSION["amounts"][$i] = $amounts[$i] * $qty;
  }
 }
 ?>
 <h2>List of All Products</h2>
 <table>
   <tr>
   <th>Product</th>
   <th width="10px">&nbsp;</th>
   <th>Amount</th>
   <th width="10px">&nbsp;</th>
   <th>Action</th>
   </tr>
 <?php
 for ($i=0; $i< count($products); $i++) {
   ?>
   <tr>
   <td><?php echo($products[$i]); ?></td>
   <td width="10px">&nbsp;</td>
   <td><?php echo($amounts[$i]); ?></td>
   <td width="10px">&nbsp;</td>
   <td><a href="?add=<?php echo($i); ?>">Add to cart</a></td>
   </tr>
   <?php
 }
 ?>
 <tr>
 <td colspan="5"></td>
 </tr>
 <tr>
 <td colspan="5"><a href="?reset=true">Reset Cart</a></td>
 </tr>
 </table>
 <?php
 if ( isset($_SESSION["cart"]) ) {
 ?>
 <br/><br/><br/>
 <h2>Cart</h2>
 <table>
 <tr>
 <th>Product</th>
 <th width="10px">&nbsp;</th>
 <th>Qty</th>
 <th width="10px">&nbsp;</th>
 <th>Amount</th>
 <th width="10px">&nbsp;</th>
 <th>Action</th>
 </tr>
 <?php
 $total = 0;
 foreach ( $_SESSION["cart"] as $i ) {
 ?>
 <tr>
 <td><?php echo( $products[$_SESSION["cart"][$i]] ); ?></td>
 <td width="10px">&nbsp;</td>
 <td><?php echo( $_SESSION["qty"][$i] ); ?></td>
 <td width="10px">&nbsp;</td>
 <td><?php echo( $_SESSION["amounts"][$i] ); ?></td>
 <td width="10px">&nbsp;</td>
 <td><a href="?delete=<?php echo($i); ?>">Delete from cart</a></td>
 </tr>
 <?php
 $total = $total + $_SESSION["amounts"][$i];
 }
 $_SESSION["total"] = $total;
 ?>
 <tr>
 <td colspan="7">Total : <?php echo($total); ?></td>
 </tr>
 </table>
 <?php
 }
 ?>

The cart example uses the following sessions to maintain the state of the cart:

$_SESSION[“qty”][i] Stores the quantity for each product
$_SESSION[“amounts”][i] Stores the price from each product
$_SESSION[“cart”][i] Identifies which items have been added to the cart
$_SESSION[“total”] Stores the total cost

The sessions are actually arrays so in the case of:

$_SESSION[“qty”][i]

is the quantity for the element with number i.

Description of the PHP shopping cart code

We start by defining PHP to use sessions by:

session_start();

This has to be at the very top of the PHP page.

Next we set up our products and populate our sessions. In this example we are using a fixed array of product descriptions and amounts. You may want to do this in your application or you could read in the data into the $product and $amounts array from a database.

//---------------------------
 //initialise sessions

 //Define the products and cost
 $products = array("product A", "product B", "product C");
 $amounts = array("19.99", "10.99", "2.99");

 if ( !isset($_SESSION["total"]) ) {

  $_SESSION["total"] = 0;

  for ($i=0; $i< count($products); $i++) {
   $_SESSION["qty"][$i] = 0;
   $_SESSION["amounts"][$i] = 0;
 }
}

The following code will reset and clear the sessions when the Reset Cart link is selected.

//---------------------------
  //Reset
  if ( isset($_GET['reset']) )
   {
    if ($_GET["reset"] == 'true')
    {
     unset($_SESSION["qty"]); //The quantity for each product
     unset($_SESSION["amounts"]); //The amount from each product
     unset($_SESSION["total"]); //The total cost
     unset($_SESSION["cart"]); //Which item has been chosen
   }
}

The following code adds an item to the sessions when the ‘Add to Cart’ link is clicked:

//---------------------------
//Add
if ( isset($_GET["add"]) )
{
$i = $_GET["add"];

$qty = $_SESSION["qty"][$i] + 1;

$_SESSION["amounts"][$i] = $amounts[$i] * $qty;
$_SESSION["cart"][$i] = $i;
$_SESSION["qty"][$i] = $qty;
}

and the following deletes an item from the cart when the ‘Delete from Cart’ link is clicked:

 //---------------------------
 //Delete
 if ( isset($_GET["delete"]) )
 {
   $i = $_GET["delete"];
   $qty = $_SESSION["qty"][$i];
   $qty--;
   $_SESSION["qty"][$i] = $qty;

 //remove item if quantity is zero
 if ($qty == 0) {
   $_SESSION["amounts"][$i] = 0;
   unset($_SESSION["cart"][$i]);
 }
 else
 {
   $_SESSION["amounts"][$i] = $amounts[$i] * $qty;
 }
 }

The rest of the code is the visual display using a table and various loops to show the product lists and the cart details together with the links.

This post is taken from part of the book PHP Tutorials: Programming with PHP and MySQL which is available as a paper back printed version or as a downloadable Kindle version. Click here for paper back version.

PHP-eSeller is a complete application that utilizes a shopping cart using PHP Sessions and is available from here:

Click here to go to PHP-eSeller

How to sell serial license keys for digital goods using PHP-KeyCodes

php license pin codesIf you sell digital products online such as software programs, games, phone PIN numbers and so on, then PHP-KeyCodes can be a useful application to install on your web site. It requires a web server running PHP and access to a MySQL database. It is easy to install with a one page install script and upload of files to your server.

PHP-KeyCodes is not just limited to distributing software license keys, you can also be use it to distribute any kind of unique key code to a customer. This could be pin numbers for mobile phone applications, TV activation systems and serial key codes for any system where there is a list of pre-generated license key codes.

If you have a requirement to sell license codes on line then this is a better method than using someone else’s web site as you do not have to pay them any fees.

Using a license system for your software program helps to prevent fraud and allows you to send free trial versions to customers. The key codes are loaded into the PHP-KeyCodes web site administration interface so that they are automatically sent whenever there is a purchase using PayPal.

The system will also send you an email when it is getting low on license keys.

The usual way to use PHP-KeyCodes is to enter the codes into the admin area so that the next code in the list is taken and sent when there is a purchase.

The PHP script has been written in such a way as to allow you to modify the program to cover other situations. So for example you may have codes in a text file that you want to upload to the server. You could modify the code to use such a text file. You could even have code that generates a key code depending on the user name or email address.

If you have particular requirements, then we would be willing to customize the code for you.

For more information: PHP-KeyCodes

http://www.withinweb.com/phpkeycodes/

Adding a virtual directory (folder) to Apache XAMPP or similar application

Suppose that you have installed XAMPP at c:\xampp This will mean you place your web files at C:\xampp\htdocs

Now you want to start developing your project, so what you could do is copy all your files to the C:\xampp\htdocs or create another folder
such as C:\xampp\htdocs\myproject

However, this is not always convenient so how do you create an alias, leaving your files where they are.

First, open the httpd.conf file, it’s located in this directory:
C:\Program Files\xampp\apache\conf

You can access this from the XAMPP control panel by clicking the “config” button.

Add these lines on the bottom of the httpd.conf file:

Alias /sources “c:/myproject”

Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
Require all granted

Note that in we must use “Forward Slash” or / in the folder definition

Restart XAMPP or stop and start Apache from the control panel.

Open your web browser and test it by go to http://localhost/myproject

New PHP script to register users on your site

PHP-Register is a new PHP / mySQL application that is used to easily create forms that collect data from your visitors before they are directed to a page of your choice.

The application is easy to instal on on Linux type web server or Windows web server providing it has PHP and mySQL.

In the administration pages you can create forms with each form having input boxes of text, textarea, drop down lists, checkboxes or radio buttons.  Each input may have validation allowing you to define the data that a visitor can enter.

For full details, refer to http://www.withinweb.com/phpregister/

Using different PHP versions on your web site

Sometimes it may be necessary to use a different version of PHP on a web folder rather than the default.  This may be when you have an application that only works on later versions of PHP as it contains functions that only work on later versions of PHP.

On some web servers this can be done using AddHandler in an htaccess file in the folder that you want a different version of PHP in.

So for version PHP 5.1

AddHandler application/x-httpd-php5 .php5 .php4 .php .php3 .php2 .phtml
AddType application/x-httpd-php5 .php5 .php4 .php .php3 .php2 .phtml

You should check with your hosting to make sure that this will work of course.

EasyPHP 12.1 bug when displaying local site

EasyPHP 12.1

If you install EasyPHP and find that it displays a blank page when you try to access the administration page, and it just sits there waiting for 127.0.0.1, then this may be caused by a bug in Internet Explorer when working with the particular version of Apache.

To overcome this, try the administration page http://localhost/home/ using FireFox or Chrome.

EasyPHP and Windows 8 64-bit

When I downloaded EasyPHP and installed it on my Windows 8 laptop, it appeared to start correctly with the EasyPHP icon in the tray, but it would not load the web pages at http://127.0.0.1

This is how I solved it:

  • from your EasyPHP short cut icon, right click and select Properties
  • select the “Compatibility” tab
  • check “Run this program in compatibility mode for:” and then select Windows 7

What to do with depreciated functions

If PHP returns messages saying that functions have depreciated, this is a warning to indicate that the code that you are running has functions in your installed version of PHP that will be removed at some time in the future by a later version of PHP.

This may occur if one day your web host suddenly decides to upgrade their servers to a new version of PHP.  You should make sure that you are on the mailing lists for your hosting company so that you will be notified of changes that may cause issues.

Depreciated functions still exist and you get warnings. So they work as expected.  However in a future version of PHP, they might disappear.  It’s a way to signal changes to users which have code based on an older PHP version.

Normally the deprecated features get removed after some time, but it’s not predictable how long this takes.

So if you see these warnings, update the code. Most often the PHP documentation has more information why something has been deprecated and what to do. Most often it’s an improvement.

Changing to a new version of PHP will mean that you will have access to the latest features of the language, however, it may mean that older versions of an application will either fail or display warning messages.

You have to decide if you want your application to operate over different PHP platforms – if you do then you have to code with common functions that are in all versions of PHP.