PHP Sessions Remove Cart Iitems - php

I have been searching around for help but can't find anything that will fix my problem
I have manipulated a cart code to serve a different a purpose Im bulging a role-play assistance site www.rptoolkit.com/encounter where you add NPC's to the encounter (Cart) and you can then remove them when needed, the site is online if you want to check
the issue is script works perfectly fine in XXMP hosting on my local host but online live, if i add 4 people to the list and try to delete 1 they all clear and the first line gets duplicated (feel free to test)
below is my script code i have used for the delete item button
<h1>Curent Encounter</h1>
<div class="encounter-table">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["encounter"]))
{
$cart_items = 0;
foreach ($_SESSION["encounter"] as $cart_itm)
{
$id = $cart_itm["code"];
$results = $mysqli->query("SELECT * FROM products WHERE id='$id' LIMIT 1");
$obj = $results->fetch_object();
echo '<td><span>
<a href="include/encounter_remove.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'"><img src="images/icon_delete.gif" alt="Delete"><
/a></span></td>';
and below is the code I have to remove items from the encounter (cart)
<?php
session_start();
include_once("config.php");
//remove item from encounter
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["encounter"]))
{
$id = $_GET["removep"]; //get the product code to remove
$return_url = base64_decode($_GET["return_url"]); //get return url
foreach ($_SESSION["encounter"] as $cart_itm) //loop through session array var
{
if($cart_itm["code"]!=$id){ //item does,t exist in the list
$product[ ] = array('code'=>$cart_itm["code"]);
}
//create a new product list for cart
$_SESSION["encounter"] = $product;
}
//redirect back to original page
header('Location:'.$return_url);
}
?>
I would love any help or advise i can I've to fix it, I don't know if its coming downy to the different PHP versions from my XXMP to the server possibly?
Thanks again,
Trev

Session variable size can be limited by the browser. Depending on how much data is stored in `$_SESSION['encounter'], you may be reaching the limit. Consider only storing a id numbers or something similar instead of more complex objects and/or arrays.

Related

How to delete items in cart with string

I have a shopping cart in my website that has uses a string for the shopping list. Each product has a 3 digit id, so the string looks something like 031181083 with 3 items.
In php,
session_start();
$numbooks = strlen($_SESSION['bookstrings'])/3;
$books = $_SESSION['cart'];
echo "You have " . $numbooks . " books in your Cart.";
echo $_SESSION['bookstrings'];
echo "<br><br>";
include '/redirect.php';
where $_SESSION['cart'] is the string that gets updated when the user adds a product to the cart.
I use a for loop with
${"book$x"} = str_replace("011", "55USD New Traditions and Encounters ", ${"book$x"});
to display the book information instead of the numbers for the user. However, I am having trouble with deleting part of the string when the user cancels the item.
The user presses
echo 'Cancel';
and redirect.php looks like this:
<?php
echo "aaa";
include 'mycart.php';
$x = $_GET['cancel'];
$booksnow = str_replace(${"bookid$x"}, "", $books);
$_SESSION['bookstrings'] = $booksnow;
echo $_SESSION['bookstrings'];
header("Location: mycart.php");
?>
When I go to redirect.php, $_SESSION['bookstrings'] is successfully updated, but when I redirect back to mycart.php, the variable resets.
I don't mind rewriting a lot of stuff, so is there a better way to code the cart? Using a string was the first thing that came to my mind, so built on top of it, but I feel like it's very inefficient, and I would love to use a simpler way with functionality.
PS: when a page opens, the php part does not show up, and when I refresh, it becomes normal. Any ideas?

Last 5 Page Names User Viewed

I'm trying to code the last 5 page names the user viewed on my site and produce it into a list. I'm currently able to get the current page name, but I don't know how to get the previous pages. This is the code I'm using to get the current page name:
<?php
$pageName = basename($_SERVER['PHP_SELF']);
echo $pageName;
?>
PHP Sessions should get you going in the right direction. For example:
session_start();
if(!isset($_SESSION['pages'])) {
$_SESSION['pages'] = array();
}
if(count($_SESSION['pages']) < 5) {
$_SESSION['pages'] [] = $_SERVER['PHP_SELF'];
} else {
echo "Limit reached";
}
print_r($_SESSION['pages']);
I recommend you use PHP Sessions to accomplish this.
So, save the current page name that you want to the sessions variable like so:
<?php
$pageName = basename($_SERVER['PHP_SELF']);
$_SESSION['pageName'] = $pageName;
?>
And then continue to save these names. #Len_D just beat me to the punch with an answer that uses arrays and is likely what you need.

php & cookies : last $articleid visited in an array

I have very little experience with cookies so I don't know how to do that.
I have a t-shirt shop where each t-shirt has an $articleID.
Each time an user visits a t-shirt page, I would like to add the $articleID to a cookie.
Then add it to an array or something so I can retrieve it later.
There shouldn't be any duplicate $articleID even if the visitor visited the same $articleID twice.
Then on the main page, I want to retrieve the list of the last 5 $articleID visited and display a list of the ID.
How could I do that?
Thanks!
in order to store an array in your cookies you will need to serialize it so check if this code will help
$articles = array();
if ( isset($_COOKIE["viewed_articles"]) )
$articles = unserialize($_COOKIE["viewed_articles"]);
if ( ! in_array($articleID, $articles)){
$articles[] = $articleID;
}
// at the end update the cookies
setcookie("viewed_articles", serialize($articles));
I hope this helps and have a loop at this link
Something like this?
<?php
$article_id = 1; // Whichever article you're currently viewing
session_start();
if ( ! isset($_SESSION['viewed_articles']))
{
$_SESSION['viewed_articles'] = array();
}
if ( ! in_array($article_id, $_SESSION['viewed_articles']))
{
$_SESSION['viewed_articles'][] = $article_id;
}
Have you tried using Sessions? Cookies will store the values on the users computer. That data is transferred to your web server on every page load.
Sessions store data on the server side. Sessions work by storing a session ID as a cookie on the user's browser which corresponds to a session stored on the server.
If you are using PHP, you can initiate a session by using
<?php
session_start();
$_SESSION['key'] = 'value';
echo $_SESSION['key']; // outputs: value
?>

Not understanding how to add cart into PHP

I am stuck on this code. I am making a web page and on the side there is a place for a cart. And with the you should be able to click on an item and add it to cart. Well I am having trouble getting it to add it to cart. Can someone help me understand what I should be doing. I have been working on it for a few days and no matter what I am doing nothing is working. If i get the code to show you have 0 in your cart it wont add anything if i try to put it in the cart.
<h1>Cart Contents?</h1>
<div class="p2">
<?php
// Get all the categories and
// link them to category.php.
// Define and execute the query:
$q = 'SELECT category_id, category FROM categories ORDER BY category';
$r = mysqli_query($dbc, $q);
// Fetch the results:
while (list($fcid, $fcat) = mysqli_fetch_array($r, MYSQLI_NUM)) {
// Print as a list item.
echo "<li>$fcat</li>\n";
if($_SERVER['PHP_SELF']!="CART FILE"){
echo "<h1>Cart Contents</h1>";
echo "<div class=\"p2\">";
$itemCount=X;
foreach($_SESSION['cart'] as X=>X){
for($i=0;$i<count(X);$i++){
$itemCount+=X;
}
}
echo "You have ".$itemCount." total items in your cart.";
echo "</div>\n";
} // End of while loop.
?>
<h1>Specials?</h1>
<div class="p2">
<p>Maybe place specials or new items or related items here.</p>
</div>
</div>
<div class="content">
Ok here is a link to what the cart should do if you look over to the side it should do what that one is doing.
http://www.programmerskit.com/advPHP/ch5/
Shouldn't
$itemCount=X;
foreach($_SESSION['cart'] as X=>X){
for($i=0;$i<count(X);$i++){
$itemCount+=X;
}
}
just be:
$itemCount = count($_SESSION['cart']);
I can't otherwise figure out what that code is supposed to be doing.
Also, that code that outputs the cart appears to be in a while loop outputting each item category, so you will be displaying the cart multiple times, which I can only assume is not desired functionality.
Also, another poster made a point about the invalid use of X as a constant, which is also a good point.
You've got a bare X used all over the place. While saying
$somevar = X;
would be legitimate if you'd already done define('X', 'somevalue') previously, this next one
foreach($_SESSION['cart'] as X=>X){
is completely invalid. You cannot assign new values to a defined constant, let alone try to assign TWO different values at the same time
foreach($_SESSION['cart'] as $key => $value)
is how that particular bit of code should be.

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";
}
?>
product.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..

Categories