Monday 28 December 2015

Recent Product History Script in PHP For Shopping Cart

<?php
    @session_start();
    if(!isset($_SESSION["lastviewed"]))    
    {
      $_SESSION["lastviewed"] = array();
    }
   
    $maxelements = 5;
    if(isset($_GET['ProductID']) && $_GET['ProductID']<>"")
    {// if we have url parameter
   
        if (in_array($_GET['ProductID'],$_SESSION["lastviewed"]))
        { // if product id is already in the array
            $_SESSION["lastviewed"] = array_diff($_SESSION["lastviewed"],array($_GET['ProductID'])) ; // remove it
            $_SESSION["lastviewed"] = array_values($_SESSION["lastviewed"]); //optionally, re-index the array
        }
   
        if(count($_SESSION["lastviewed"]) >= $maxelements)
        {//check the number of array elements
            $_SESSION["lastviewed"] = array_slice($_SESSION["lastviewed"],1); // remove the first element if we have 5 already
            array_push($_SESSION["lastviewed"],$_GET['ProductID']);//add the current itemid to the array
        }
        else
        {
            array_push($_SESSION["lastviewed"],$_GET['ProductID']);//add the current itemid to the array
        }
    }
   
    echo "<pre>";
    print_r($_SESSION["lastviewed"]);

?>