abdallah al sawaqi
abdallah al sawaqi

Reputation: 73

Cant load cookie data to another page

I am trying to retrieve cookie data that has been set from another page but i cant seem to view that data, but if i fetch it in same page it will work

I have tried some methods but its still not working even after i refresh the cookies from the browser

This is code from the add.php page

<form method="post">
    <input type="text" name="quantity" value="1" class="form-control" />
    <input type="hidden" name="hidden_name" value="<?php echo $row["name"];?>" />
    <input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />
  <input type="hidden" name="hidden_id" value="<?php echo $row["id"]; ?>"/>
  <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
</form> 

if(isset($_POST["add_to_cart"])) {
    if(isset($_COOKIE["shopping_cart"])) {
        $cookie_data = stripslashes($_COOKIE['shopping_cart']);

        $cart_data = json_decode($cookie_data, true);
    } else {
        $cart_data = array();
    }

    $item_id_list = array_column($cart_data, 'item_id');

    if(in_array($_POST["hidden_id"], $item_id_list)) {
        foreach($cart_data as $keys => $values) {
            if($cart_data[$keys]["item_id"] == $_POST["hidden_id"]) {
                $cart_data[$keys]["item_quantity"] = $cart_data[$keys]["item_quantity"] + $_POST["quantity"];
            }
        }
    } else {
        $item_array = array(
                  'item_id'   => $_POST["hidden_id"],
                  'item_name'   => $_POST["hidden_name"],
                  'item_price'  => $_POST["hidden_price"],
                   'item_quantity'  => $_POST["quantity"]
                  );
        $cart_data[] = $item_array;
    }


    $item_data = json_encode($cart_data);
    setcookie('shopping_cart', $item_data, time() + (86400 * 30),'/');
    header("location:show.php");
}

This is the code for retrieving cookie data from add.php,this code is another page called show.php

<?php
if(isset($_COOKIE["shopping_cart"])) {
    $total = 0;
    $cookie_data = stripslashes($_COOKIE['shopping_cart']);
    $cart_data = json_decode($cookie_data, true);

    foreach($cart_data as $keys => $values){
?>  

        <p> <?php echo   $values["item_id"];?></p> 
        <p> <?php echo   $values["item_quantity"];?></p> 
        <p> <?php echo   $values["item_name"];?></p> 
        <p> <?php echo   $values["item_body"]; ?></p> 

<?php
    }
}
?>

All i want to do is to get the cookie data that is been set from the add page to be displayed on the show page

Upvotes: 0

Views: 90

Answers (1)

Abdallah
Abdallah

Reputation: 198

try putting the header first then set your cookie

Like this:

  header("location:show.php");  
  setcookie('shopping_cart', $item_data, time() + (86400 * 30),'/');

Upvotes: 1

Related Questions