I am building my own php cart for the past week and I got stuck in some issues.
I managed to add new items in the cart, and the URL looks like below.
http://blah-blah.com/order/index.php?action=add&id=84
The question is simple: How can I prevent from adding the same item again in the cart
if someone refreshes the page? Cause now every time someone refreshes the page, it changes the quantity to +1 for the specific item..
Also, after moving to the checkout page, if they press the back button in the browser, AGAIN the quantity will change to +1;
Any recommendations?
Yea. Have them set, rather than increment the quantity.
Also, you'd usually use POST (not GET) requests for this sort of action. Browsers know this and cunningly ask the user whether they want to re-submit POST data.
The cleanest approach for your user may be to do the whole thing with AJAX. If they go "back", they'll just go back to the last page they visited without trouble. This would be equivalent to how comments on Stack Overflow are submitted: you cannot go "back" to your submission step and end up writing duplicate comments.
I would suggest following steps to avoid multiple submission and back button issues:
As suggested above you should use POST method to submit your form instead of GET.
Prevent multiple form submission from the same session as described here: http://phpsense.com/php/prevent-duplicate-form-submission.html
After you're done with processing the POST request you should redirect to a confirmation URI OR better to the same URI as follows:
// redirect after processing the POST request
header("Location: " . $_SERVER["REQUEST_URI"]);
exit;
As said by Tomalak it's better to use POST datas for thoose kind of action.
An other point you can use in conjunction with POST datas is to respond to the user with a redirect header then even if he try to refresh or go back the data won't be processed again.
basic example:
<?php
if( !empty($_POST) ){
// do stuff with POST datas then
header("location: mypage.php\n");
exit;
}
You can use
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
To redirect your user to the previous page? Pressing refresh or the back/forward buttons will not load the add page again.
I know this question is closed, But i have an alternative that I thought up for this exact problem.
The idea is to create a hash of $_POST data before and after. For this example i used md5, but you can use whatever algorithm you want:
$postHash = md5(serialize($_POST).date("dMY",time()));
if(!isset($_SESSION['post'])) $_SESSION['post']="Not yet set.";
Then all your processing code that would normally go at the top of the page you simply put into the following IF:
if($_SESSION['post']!=$postHash) {
// Perform actions
} else {
echo "Cannot post duplicate data";
}
Then, at the bottom of the page (or after processing has complete, and any database calls have been actioned):
$_SESSION['post'] = md5(serialize($_POST).date("dMY",time()));
There are still a few problems but it seems to work okay. Hope this helps.
Hi I don't have a coding solution for you but rather a logical solution to this problem give it a try it might help you, it helped me
I faced the same problem where I used the "ShoppingCart?AddToCart=1&....." in my URL(GET Variable) as a way of knowing that the user wants to add products to the cart and every time I refreshed the page the same product got added again and again
My way of working when I received the AddToCart Request was to first execute a method that will add the product to cart and then execute another method that will display the contents of the cart (THIS WAS THE PROBLEM RIGHT HERE)
I changed the logic a bit
Now whenever I receive the same AddToCart Request I execute the same first method to add the contents to the cart
BUT
Now rather than executing the second method to display the content of the cart I use the header("Location: ShoppingCart?ViewCart=1")
This means that after executing the first method which add the content to the cart I make a ViewCart Request to my Shopping Cart page, now every time I make a AddToCart Request it properly adds the contents to the cart and after that whenever I try to refresh the page to try to replicate the AddToCart Request I always end up with ViewCart Request and the Page simply shows the Cart contents and not add any futher contents to the cart
The trick over here is that every time I receive the "ShoppingCart?AddToCart=1&....." I execute the Add function and the header function in such a way that I end up with displaying "ShoppingCart?ViewCart=1" in the URL rather than the original "ShoppingCart?AddToCart=1&....."
Now even if some tries to refresh the page or comes back to the page using Back Button in the browser they always end making a "ShoppingCart?ViewCart=1" Request, they never see the "ShoppingCart?AddToCart=1&....." in the URL
like I said I don't have a Coding Solution but rather a Logical Solution
Hope this helps
Related
I have a web page that loads all the data from a mysql database called datalist.php
From this page I can edit record by record with a button that redirects you to an editdata.php page adapted to the fid of the record.
Once edited as they want to see the changes, I don't redirect them to the main one letting them see the changes and simply clicking back or with a button they return to the datalist.php without any problem.
The button is this
echo "<p id='parrafo'><a style='padding:1px 20px'class='button rounded-0 primary-bg text-white w-0 btn_1 boxed-btn' href='javascript:history.back() '><--</a></p>";
PROBLEM
I added a search engine where the displayed data can be filtered.
When they use the search engine from datalist.php, I direct them to a page called search engine.php where, through a post method, I store what they are looking for in a variable and the data that users want appears.
But when they edit a filtered record, it is edited without problems, but when they go back, they return to the search engine.php and the message appears:
"Confirm form resubmission In order to display correctly, this web page needs the data you entered earlier. You can submit that data again, but that will cause the page to repeat all previous actions. Press Reload to submit the data and display the page.
Hit the page refresh button to resubmit the data needed to load the page."
Of course, if they update, they come back when the filtered data comes out.
Isn't there any way to store the variable used in the search so that when I go back I don't get this error or any solution??
simple! when user will submit form for that variable instead of making post request
option1: just use get request __url__?variable=... but this will not remember the variable when you go back
option2: store the variable in the cookie and just go to next page (eg. window.location.href = '...';). and in next page access the cookie from php.
If you are wanting to show the form to the user as a confirmation, but without the possibility of another post, then remove the form element and the button. Display all other boxes as they are (with the values populated from the POST array).
And display another message telling them that it has been successful.
You are using PHP, you can achieve this easily with it. If you are unsure, then post a short version of your code in a separate question.
Good day, as the title says, how can I do that? What I'm trying to do is that on page 1, I looped all data with each having a button that has value of their specific id, then that button redirects to a common page 2, then I use that id on page 2 to display their whole data, but the problem is that when I refresh, the dialog appears.
I tried using session, but the problem is that when multiple tabs are accessing it.
I haven't really tried PRG, but on my understanding, it is used to send changes to the server using another page, then redirect to the previous page, preventing the dialog when refreshing. I thought of using it, but I don't know how to send the fetched data from page 1.5 to page 2
I'd be really grateful for a solution to this, or if someone can link me to similar problems. Maybe this is a duplicate question, but I just can't find the term for my problem. Cheers!!
If you control both pages, change the redirect mechanism on page 1 to GET by simply redirecting to a URL with a parameter appended to the address: target.php?id=42.
If you control only page 2, you may convert a POST request with an id to a GET request:
if (isset($_POST['id']))
{
header('Location: target.php?id=' . $_POST['id']);
exit;
}
More on GET vs POST here, as well as a couple of other answers.
I'm working on wordpress plugin, which handles shopping cart. I have two pages, checkout and thank you page. Items to cart are added by link like that https://mysite.com/checkout/?action=add&subscription=23 . I'm using Session for adding items to the cart on checkout page.
Suppose if I add three items added:
https://mysite.com/checkout/?action=add&subscription=1
https://mysite.com/checkout/?action=add&subscription=2
https://mysite.com/checkout/?action=add&subscription=3 (Last link in browser addressbar)
When user checkout on checkout page then user is redirected to thank you page. I have problem with browser back button, If user press back button on thank you, he is redirected again to checkout page with last item again added (https://mysite/checkout/?action=add&subscription=3 ) since this was the last link in browser address bar.
How can i prevent browser to add last item again on user back button press on thank you page?
Is there any way in PHP to detect if request is coming from browser back button? I think, there can be way to handle it using session?
Please guide me if there is any other suitable way to accomplish this? Thanks
The best way to handle that is to use the POST/REDIRECT/GET pattern.
Use Post Redirect Get design pattern.
In other words, the script that processes is not the one that displays the results.
You can user
$_SERVER['HTTP_REFERER'] to see your parent page, and detect if user is coming from thank you page
Lets say I have a Page with a List (list.php).
I click on a row on that list to Edit that record. I go to a edit.php Page.
I have 3 buttons on that edit.php page. Save, Apply, Cancel
Save button - Saves the Record and returns to the (list.php) Page
Apply button - Saves Record but stays on the same page (edit.php)
Cancel button - No save, just return to the (list.php) Page
But now image if I can access for edit that item on a different page. How do I return to that calling page?
Do I add a parameter(code) to the URL? something like a Page Origination Code?
Do I save the previous page URL in a session? (bad, they can right click open another page and that would be saved to session url)
Am just curious to how others return to a previous page after a SAVE.
you can the server variable $_SERVER['HTTP_referrer'].
They are other ways also you can store in session the current page and use is processing page.
Adding a parameter to the URL is the only reliable though quote ugly way.
That's why such an in-place editions nowadays often being implemented using AJAX, and this very site is a perfect example.
However, there are different cases.
Login page is imperfect example for example, as you always have a form instead of just a link, and thus you can always store the current page in a hidden form field.
Another approach is possible if you are using some sort of front controller, and all requests actually being directed to the single index.php file which runs appropriate script based on the URI.
in this latter case you will need no more than mere a redirect to the current page.
I have a function that imports a files contents into mySQL and returns the results. If i refresh the page and click "yes" it will do it again doubling the output with the same content.
How can I stop this happening? In this particular case there is no URI in the address bar but on other functions there is.
You should just check if the contents in the database exist, if they don't, fill them. Otherwise don't run the function.
psuedo-code:
if !database.containsRecords
fillDatabase()
end
On top of this, it is always good practice to redirect after a POST request. So you would want:
fillDatabase();
header("Location page.php");
exit();
Query the database on each page load and see if it has already been populated. If it has been populated then don't attempt to populate it again.
You should use the POST-redirect-GET pattern.
After updating the database, send an HTTP redirect to a separate page that displays the results.
Refreshing the browser will reload that separate page.
I assume you use a POST form to upload the file.
You can include a hidden input field with an pseudo random unique id in your form.
If the user resends the data via POST you can check if you already processed this request.
Hidden fields are not save because a user might edit them, but you can detect accidental resubmits.