Not displaying cookie count correctly
I have one file basket.php
that displays the count perfectly, but in the other php file product.php
it always displays 0 the codings are below:
basket.php
<?php
//include(dirname(__FILE__)."/../config.php");
if (isset($_COOKIE["products"])) {
//Count of all products in basket
$BasketCount = count($_COOKIE['products']);
//Loop through and get each cookie
foreach ($_COOKIE['products'] as $name) {
$name = htmlspecialchars($name);
echo "$name <a href='remove.php?remove=$name'>Click here to remove from basket</a> <br />\n";
}
echo "Basket Count: $BasketCount";
}else{
echo "Basket is empty";
}
?>
pro开发者_开发技巧duct.php (just the line that gets the basket count)
$basketcount = count($_COOKIE['products']);
Here is how i set the cookies
addtobasket.php
<?php
include(dirname(__FILE__)."/../config.php");
$product = $_GET['p'];
setcookie("products[$product]", $product);
echo "$product added to basket";
//Show current basket products
?>
May be issue with path - http://www.php.net/manual/en/function.setcookie.php, $path
parameter. Or domain.
Not the actual answer, but nevertheless related:
Assuming you're making a commercial website with a basket/shopping cart system, I would advice this: DO NOT RELY ON COOKIES, never. It's stored on client side and can be modified easily. Moreover some browser simply refuses them, and thus your basket won't work.
Use $_SESSION[]
instead, they only store the identifier client side. Safer, both against hacking code flaws and anything.
may be you are running product.php before cookie is set..
other than that code is fine to me.
or you can check cookie is set or not by this code..
if(isset($_COOKIE['products'][$product])){
echo "cookie is set..";
}
so that you will have exact idea..
精彩评论