Storing cart items in browser using php cookies

25 Views Asked by At

Anytime I clear cookies and refresh the page, I think null is added to the cookies and the total items added to cart shows as 1 but nothing shows in the cart which makes me get this error when calculating for the total cart price "Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\e-commerce\functions\common_functions.php on line 593 0 "

I want nothing to be added to the cookies until I add an item to cart manually

This is the code for adding of items in the cookies

function addToCart($productId)
{
    // Initialize an empty array to store cart items
    $cartItems = array();

    // Check if the 'cartItems' cookie is set and not empty
    if (isset($_COOKIE['cartItems']) && $_COOKIE['cartItems'] !== '') {
        // Attempt to decode the cart items from the cookie
        $decodedCartItems = json_decode($_COOKIE['cartItems'], true);

        // Check if the decoding was successful and it's an array
        if (is_array($decodedCartItems)) {
            // Use the decoded cart items
            $cartItems = $decodedCartItems;
        } else {
            // If decoding failed or the result is not an array, log an error or handle it accordingly
            echo "<script>console.error('Error decoding cart items from cookie');</script>";
        }
    }

    // Check if the product is already in the cart
    if (in_array($productId, $cartItems)) {
        // If the item is already in the cart, no need to add it again
        return;
    }

    // Add the product ID to the cart items array
    $cartItems[] = $productId;

    // Encode the cart items array as JSON and store it in a cookie
    $cartItemsJSON = json_encode($cartItems);
    setcookie('cartItems', $cartItemsJSON, time() + (86400 * 10), '/'); // Expires in 10 days

    // Check if the product was added to the cart
    echo "<script>console.log('Cart items present in cookies:', $cartItemsJSON)</script>";
    echo "<script>alert('Item Added To Bag')</script>";

    // Redirect back to the same index page after processing
    echo "<script>window.location.href = 'index.php';</script>";
    exit; // Stop further execution of PHP script
}

// Check if 'add_to_cart' parameter is set in the URL
if (isset($_GET['add_to_cart'])) {
    // Get the product ID to add to cart
    $product_id = $_GET['add_to_cart'];

    // Add the product to the cart
    addToCart($product_id);
}
0

There are 0 best solutions below