Hi,

I have created a simple shopping cart using session array, selected products are stored in the table. So far I have no problem!

I wish to remove (using x) individual product from the table/array, but I cannot access it.

Is anyone SESSION expert who can help?
Thanks in advance!


Printed table / session vector:
Art01 product_1 qte_1 price_1 image _1 x
Art02 product_2 qte_2 price_2 image _2 x
Art03 product_3 qte_3 price_3 image _3 x

My code:
$_SESSION["varukorg"][] = array(

"artikel" => $_SESSION,
"produkt" => $_SESSION,
"antal" => $_SESSION,
"pris" => $_SESSION,
"image_cart" => $_SESSION
);


foreach($_SESSION as $cart)
{
echo "<p>" . $cart . "</p>";
echo "<p>" . $cart . "</p>";
echo "<p>" . $cart . "</p>";
echo "<p>" . $cart . "</p>";
echo "<p><a href=#><img src=\"/images/produkter/ $cart \" width=100 height=100/></a></p>";
echo "<p><a href=#>delete</a></p>";
}

Dani AI

Generated

You are on the right track. Two common pitfalls showed up in the early snippets: storing entire $_SESSION into each cart field (use scalars, not the whole superglobal), and unsetting the wrong path (e.g., $_SESSION['varukorg']['product'] deletes a literal key named "product" rather than the selected item). corrected the array path and indexing, and highlighted the need for a stable key. A practical pattern is to give every cart row its own immutable line id so you can safely delete the exact row even when the same product appears multiple times.

Here is a minimal, robust delete flow that avoids GET for destructive actions and supports duplicate items:

<?php
session_start();

if (empty($_SESSION['csrf'])) {
  $_SESSION['csrf'] = bin2hex(random_bytes(16));
}

// Example add (use your own inputs)
function cart_add($art,$product,$qty,$price,$image) {
  $lineId = bin2hex(random_bytes(8));
  $_SESSION['varukorg'][$lineId] = [
    'artikel'=>$art, 'produkt'=>$product, 'antal'=>(int)$qty,
    'pris'=>(float)$price, 'image_cart'=>$image
  ];
  return $lineId;
}

// Handle delete
if ($_SERVER['REQUEST_METHOD']==='POST'
    && isset($_POST['id'], $_POST['csrf'])
    && hash_equals($_SESSION['csrf'], $_POST['csrf'])
    && isset($_SESSION['varukorg'][$_POST['id']])) {
  unset($_SESSION['varukorg'][$_POST['id']]);
  header('Location: '.$_SERVER['PHP_SELF']);
  exit;
}

In your table, render for each $lineId:

<form method="post">
  <input type="hidden" name="id" value="<?php echo htmlspecialchars($lineId, ENT_QUOTES); ?>">
  <input type="hidden" name="csrf" value="<?php echo $_SESSION['csrf']; ?>">
  <button type="submit">delete</button>
</form>

Troubleshooting tips:

  • Call session_start() before any output; verify the session id stays the same across requests.
  • After unset, re-render the table from $_SESSION['varukorg']; avoid caching old HTML.
  • If you rely on numeric indexes, call $_SESSION['varukorg'] = array_values($_SESSION['varukorg']); after deletions.
  • Always escape output (e.g., htmlspecialchars) when printing product names or image paths.

Recommended Answers

All 15 Replies

try:

foreach($_SESSION['varukorg'] as $index=>$cart)
{
echo "<p>" . $cart['art'] . "</p>";
echo "<p>" . $cart['product'] . "</p>";
echo "<p>" . $cart['qte'] . "</p>";
echo "<p>" . $cart['price'] . "</p>";
echo "<p><a href=#><img src=\"/images/produkter/ $cart['image_cart'] \" width=100 height=100/></a></p>";
echo sprintf("<p><a href='%s?id=%s&action=d'>delete</a></p>",$_SERVER['PHP_SELF'],$index);
}

so when you click on the Delete button, it will send the id of the item to be deleted. So start your page with:

<?php
session_start();

if( isset($_GET['action']) && $_GET['action']=='d' && isset($_GET['id']) && isset($_SESSION[ $_GET['id'] ]) ) 
{
  unset($_SESSION[ $_GET['id'] ]);
}

Thanks for help hielo,

I may still not unset the data from the Session arrays...


Best regards
new web

I may still not unset the data from the Session arrays...

What does that mean? Have your resolved the problem? If not, on the page where you are setting/initializing the $_SESSION, you MUST call session_start() first (preferable at the very start or your file).

I have not solved the problem yet, I call session_start() first at the start on every page.

There correct syntax for the foreach that you posted originally should be:

foreach($_SESSION['varukorg'] as $index=>$cart)
{
echo "<p>" . $cart['artikel'] . "</p>";
echo "<p>" . $cart['produkt'] . "</p>";
echo "<p>" . $cart['antal'] . "</p>";
echo "<p>" . $cart['pris'] . "</p>";
echo "<p><a href='#'><img src='/images/produkter/{$cart['image_cart']}' width='100' height='100'/></a></p>";
echo sprintf("<p><a href='%s?id=%s&action=d'>delete</a></p>",$_SERVER['PHP_SELF'],$index);
}

Thanks for help hielo,

I have corrected the syntax, but it does not work yet

Best regards
newweb

I think what you are supposed to do is as follows:
- When you save your array in the session, you need to uniquely identify each array you store in the session ie Instead of this code you use

$_SESSION["varukorg"][] = array(

"artikel" => $_SESSION['art'],
"produkt" => $_SESSION['product'],
"antal" => $_SESSION['qte'],
"pris" => $_SESSION['price'],
"image_cart" => $_SESSION['image']
);

Place the product(or some unique key for each shopped item) as the key in your session array ie.

$productKey = $_SESSION['product']; // new code to add
$_SESSION["varukorg"][$productKey] = array(

"artikel" => $_SESSION['art'],
"produkt" => $_SESSION['product'],
"antal" => $_SESSION['qte'],
"pris" => $_SESSION['price'],
"image_cart" => $_SESSION['image']
);

Then, when you now want to delete a particular product, loop in the session, searching for the array item with the particular key.
ie.

$productToDelete = $_REQUEST['product']; //product marked for deletion on the webpage

//deleting a particular item
foreach($_SESSION['varukorg'] as $cart)
{
  if($cart['product'] == $productToDelete)
  {
    unset($_SESSION['varukorg']['product']); // delete the product
    break; // exit the loop
  }
}

Thanks so much wilch for your help,

Please, how can I active delete link?

echo "<p><a href=varukorg.php????>delete/></a></td>";

Best regards

sam

Depending on whatever unique key you are using to identify each added product, it is this key that you must use in the anchor tag's url. eg. In my last example my unique key was product, therefore i'd write <a href="varukorg.php?product=$product&action=delete">delete</a> Then somewhere in my php file check for the 2 variables $_REQUEST & $_REQUEST, if the action is 'delete', then delete the product from the $_SESSION variable, as illustrated in my earlier code.

Thanks again wilch,

Now I can see a particular product with the particular key (when the mouseover the link) in the session table: foreach($_SESSION['varukorg'] as $cart …) But when I click delete link, the particular product not removed from session table yet.

echo "<p><a href=varukorg.php?product=$cart[product]>delete></a></p>";


if(isset($_REQUEST['product'])) //  
{   
    $productToDelete = $_REQUEST['product']; 

    foreach($_SESSION['varukorg'] as $cart)
    {
      if($cart['product'] == $productToDelete)
      {
        unset($_SESSION['varukorg']['product']); // delete the product
        break; // exit the loop

      }
         }                        

}

newweb, whenever you post code, please use the CODE "button" on the editor.
The following should work. Be sure to COPY AND PASTE:

<?php
session_start();

$_SESSION["varukorg"][] = array(

	"artikel" => $_SESSION['art'],
	"produkt" => $_SESSION['product'],
	"antal" => $_SESSION['qte'],
	"pris" => $_SESSION['price'],
	"image_cart" => $_SESSION['image']
); 

if( isset($_GET['action']) && $_GET['action']=='d' && isset($_GET['id']) && isset($_SESSION[ $_GET['id'] ]) ) 
{
  unset($_SESSION['varukorg'][ $_GET['id'] ]);
}

foreach($_SESSION['varukorg'] as $index=>$cart)
{
	echo "<p>" . $cart['artikel'] . "</p>";
	echo "<p>" . $cart['produkt'] . "</p>";
	echo "<p>" . $cart['antal'] . "</p>";
	echo "<p>" . $cart['pris'] . "</p>";
	echo "<p><a href='#'><img src='/images/produkter/{$cart['image_cart']}' width='100' height='100'/></a></p>";
	echo sprintf("<p><a href='%s?id=%s&action=d'>delete</a></p>",$_SERVER['PHP_SELF'],$index);
}

?>

Hi and thanks hielo,

I copied and pasted the code, but the particular product not removed from session table yet.
I do not know what I'm doing wrong. I can see a particular product with the particular key in the session table.

Thanks again for your help

!

newweb

my apologies. There's an error in the if clause. It should be: if( isset($_GET['action']) && $_GET['action']=='d' && isset($_GET['id']) && isset($_SESSION[B]['varukorg'][/B][ $_GET['id'] ]) )

If you are to use Hielo's method above, try changing line 13 to if( isset($_GET['action']) && $_GET['action']=='d' && isset($_GET['id']) && isset($_SESSION['varukorg'][ $_GET['id'] ]) ) I presume, he forgot to add the bigger array name "varukorg"

Many, many thanks hielo and wilch,

Thanks for your help, thanks for the time you spent with me
Now it works like charm!

Your help has been very useful for me!

Best regards!
newweb / sam

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.