views:

139

answers:

2

Hi, I'm new to PHP and in order to learn the language and the concepts I'm working on a e-commerce website with a shopping cart, etc. In this site I have items, when an item is clicked, the id of the item is sent via the GET method to the shopping cart page. Using this id, I add the item to the shopping cart(table in db) and it works fine.

<a href="do_shoppingcart.php?id=<?php echo "$itm_id"; ?>">

The issue is; if the user clicks the refresh button, the item is added again to the shopping cart. Do you think that disabling the refresh button or F5 button is a good option? what must i do to prevent the user from adding the item to the shopping cart when the page is refreshed? In forms I've noticed that "(isset($_POST['Submit'])){}" is helpful, but for the GET method this doesn't work accordingly.

Your help is appreciated.

A: 

you should do destructive actions with POST, reserve GET for idempotent operations.

just somebody
That wouldn't necessarily help. The user could still refresh the page and then agree to resend the data...
Franz
well the browser warns you that you're going to repeat the last action. it doesn't do it for GETs, because those *should* be nondestructive.
just somebody
Well, there are enough people who could misunderstand that. Just look at all the less tech-interested people you might know that would just click "OK".
Franz
it'll still prevent your users from bookmarking a destructive URL (saw this happen with a legacy app: a user set such a URL as their home page)
just somebody
A: 

The safest way (also helpful to prevent CSRF attacks) is to add a token as hidden field to your form. Then, in the processing script, only add the item to the database if that token does not exist yet...

The token could be created by something like this:

$token = sha1(uniqid());

Appended to your link:

echo '<a href="process.php?id='.$id.'&token='.$token;

Then, when processing, you query your database for a line with that token.

SELECT 1 FROM table WHERE token='abc....'

If this query returns a result, don't process anything else...

Franz
I should help that just adding the token will not help to prevent CSRF attacks. A little more would have to be done, but that's another topic again...
Franz
@Franz-I'm not using a form in the shoppingcart page, where i'm using the id sent via GET method. It's just a simple script.
pier
That's fine, too. Just add a token to the URL then.
Franz
@Franz-sorry, I'm new to PHP. How must I do this? Thnx
pier
I edited my answer.
Franz
@Franz-Thank you, I found another way and I think it's much simpler. I applied the isset function to a session variable and determined the state. Based on this the appropriate script is executed. :)
pier
That is, **if** sessions work :P
Franz