PHP- refreshing a page that contains '?var=value' - php

I am developing a courier application using PHP and MySQL and I have come across a minor bug. Say, I have a page that adds a new shipment (add.php). Upon filling the details and clicking on "submit" button in the form, addshipment.php is fired which contains the code to add the new shipment to the sql table. If the data is entered successfully, the following code will execute:
header("location:add.php?add=success");
Thus, the add.php page will reload with the URL "add.php?add=success" with an alert box that will say that data has been inserted successfully. That alert box is executed via the following code at the bottom of the page:
if(isset($_GET['add']))
{
switch($_GET['add'])
{
case "invalid":
echo "<script>alert('Please fill all the fields');</script>";
break;
case "fail":
echo "<script>alert('Your data was not inserted successfully');</script>";
break;
case "success":
echo "<script>alert('Your Data was Added Successfully');</script>";
break;
}
}
Works fine but every time I refresh the page I get the same alert box since the URL still contains ?add=success. I wish the add.php page not to contain the values after data insertion but still display the alert message. Any ideas?
Thanks

The common solution for this issue is to store messages in session and remove them once displayed. Many frameworks have appropriate mechasnim included (eg. Zend Framework has FlashMessenger).
You may also create such mechanism on your own, it's pretty simple. The most basic usage may look as follows:
// put any message in $_SESSION['message'] BEFORE redirection
$_SESSION['message'] = 'success';
header("location:add.php");
And then at the bottom of the page:
if(isset($_SESSION['message']))
{
switch($_SESSION['message']) {
case "invalid":
echo "<script>alert('Please fill all the fields');</script>";
break;
case "fail":
echo "<script>alert('Your data was not inserted successfully');</script>";
break;
case "success":
echo "<script>alert('Your Data was Added Successfully');</script>";
break;
}
// do not display this message again
unset($_SESSION['message']);
}
Don't forget to call session_start somewhere at the top of your code.

Replace success in the URL with a message ID.
Store the message in a database, associated with the ID.
After the ID has been requested, generate the page with the alert and then mark the message in the database as seen (or delete it entirely).
If another request for the same ID comes in, don't include the alert (or redirect to the URL with the query string on the end).

We need to use name for submit button. It's need to get values from the form if submit button is click. Then we can check whether we click the submit button.
Assume name of submit button is "submit". Then:
if (isset($_POST[submit]))
{
/* do the form validation and processing here. */
}
This is the way we can check we see this page for the first time or whether we click submit button. URL will not change. Therefore alert message wont pop-up when we refresh the page. Just use $_POST[] instead of $_GET[].

Related

set commands for the condition "I'm redirected to another page" (php)

I'm using php
I have a process form for a comment page that when you click on submit, you will be redirected to the main page of the website
when I redirected to index.php from my processform.php, I want to see an alert in my index that "Your comment was saved!" (It needs that my index page understand that I'm coming from processform.php)
How can I do this?
you should use something like sessions.
set session on submit form. and on index.php check if session has set with the special key. then show the alert that you want.
on form submit and success :
// Start the session
session_start();
// Set session variables
$_SESSION["processform"] = "Your comment was saved!";
on index.php
if(isset($_SESSION["processform"]){
// do alert
}

How do I use a PHP session to prevent duplicate form submissions?

I want to stop duplicate form submissions to my webpage. Everywhere I look for help, I see use a $_SESSION variable; but I fail to see how sessions and forms could possibly connect to each other outside the context of multiple user accounts.
Can someone show me exactly how this process works?
Edit: I don't want to stop the form being submitted multiple times; only to prevent resubmitting the form with the same values (on page refresh for example).
After the form is processed, the user should see a success/error message and then the form again.
Basically you need to use the unique SESSION value twice. Once somewhere in the form you are trying to submit and once stored in the $_SESSION variable. When the form is POSTED and both values are a match then we have a successful submission, when the form is POSTED but the values are different, no submission occurs.
I.e.:
somewhere on the top of your PHP page:
<?php
session_start(); // first line of your PHP page
$_SESSION['secretFormValue'] = isset($_SESSION["secretFormValue"]) ? $_SESSION["secretFormValue"] : md5(microtime()); // generate some unique session value
// assign submitted **secretFormValue** from your form to a local variable
$secretFormValue = isset($_POST["secretFormValue"])? filter_var($_POST["secretFormValue"], FILTER_SANITIZE_STRING) : '';
// check if the value is present in the **secretFormValue** variable
if($secretFormValue != '') {
// check if both values are the same
if($_SESSION["secretFormValue"] == $secretFormValue) {
// Process form values & submission ...
// add your own code...
unset($_SESSION["secretFormValue"]);
} else {
echo "Duplicate submission";
}
} else {
// do some other thing
}
somewhere below in your form:
<input type="hidden" name="secretFormValue" value"<?php echo $_SESSION['secretFormValue']; ?>">
***I did not test this so please comment in case there is a bug, thx.*
Edit:
If you need to prevent submit on page-refresh you may include clearing all the POST values on successful submit so the refresh would fail because of the empty POST i.e.:
unset($_POST); // place it right before unset($_SESSION["secretFormValue"]);
or
Include a redirect to a different page (i.e. Thank You Page) after submission i.e.:
header("Location:ThankYouPage.php"); // place it right after unset($_SESSION["secretFormValue"]);
or just found this one in other SO post:
https://en.wikipedia.org/wiki/Post/Redirect/Get
You could simply set a $_SESSION['submittedForm'] = true; variable once the form is submitted by that visitor. You could then check for that session data next time they visit the form page and either not show the form, or throw an error message if they try to submit it again.
I suggest an alternative approach. The problem you're trying to solve comes in two variants:
How can I prevent/detect a form from being submitted multiple times (usually accidentally) when the user refreshes the page after submitting?
How can I prevent the submission (or at least make it harder) of form data not coming from an actual form shown on my page?
The solution by Milan solves to both problems, but creates a problem on its own: if the user has the same page open in multiple tabs/windows (remember, they share the same session), this will break.
If you don't care about problem #2, it would be easier to do a "passive" approach, by keeping a list of form IDs in your session data that have already be submitted:
$formID = (isset($_POST["__form_id"]) ? $_POST["__form_id"] : false);
$submittedforms = (isset($_SESSION["submittedforms"]) ? $_SESSION["submittedforms"] : array());
// Check whether this form ID has been submitted before
if (in_array($formID, $submittedforms)) {
printf("Duplicate submission.");
exit;
}
// Store the ID of this form submission
$submittedforms[] = $formID;
$_SESSION["submittedforms"] = $submittedforms;
// Continue form processing...
If you need to prevent unauthorized (automated) form submission too, an active approach is needed. I would extend Milan's solution then to store multiple form IDs in your session data (in an array), one for each form generated; and then remove them one-by-one as they are submitted.

How to Validate a form in within the same page and when there are no errors send it to another page for further registration?

Okay. I have yet another easy problem which I can't solve. I am working with PHP and I am working on a form to be validated by PHP. I have validated the form in another page containing the same elements. That's the
<form name = "Order Form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">
but now the problem arises is that, when we have validated the form and there are no more errors, how to send the data for further registration in other pages. Assuming that Javascript is off I have to use this method. Help is very much appreciated.
You can use session to store some data for a short time such as registration process example:
<?php session_start();
if(noerror){
$_SESSION['username']=$username;
//similarly do for more
header("Location:next_page.php");
}
else{
//show error
}
Note: Alternatively You can also use hidden input but I will discourage that as for security purpose you need to re-validate that.
Update:
To check if an error has occurred or not no need to count them simply use an variable called $noerror and initialize it with TRUE and as soon as an error occurs set it to false then simply put it in if($noerror) at last.
If you want to display error message store them in an array like $error_log
example:
if(error_in_username){
$noerror=false;
$error_log['username']="Invalid Username";
}
Please refer to below link.
http://www.w3schools.com/php/php_form_url_email.asp
Hope this will solve your problem.
On your validation 'page' which should be a controller of sorts, if validation is successful, load the step2 page with the previous form data in hidden inputs.
OR
After successful validation of step1, save the data already into database (could be a temp table), and then proceed to step2 with the id of the entry you just saved. On submission of step2, you can merge the step2 data with the data of the entry that was saved in the database, and proceed to step3 if necessary. etc.
If you simply want to get to another page, the basic logic is:
if(validation_success)
{
header("Location: step2.php");
} else {
show_errors();
}

Query runs as many times as one does refresh

If possible i'd need help with a reload thing. I mean i have this query, which gets submitted in one page, there is this profile registration, user enters his name and surname, then he proceeds in the next page entering more specific details. if a user reloads the page i.e 4 times, that's the number of times that the user's information get inserted in the database.
is there any reload function to prevent the submission of the query?
I haven't tried anything, if you would ask me that, because i don't know how to start. the only clue i have is about using ajax, but is there any php way to do this?
Thanks
You should follow the POST-Redirect-GET pattern and ALWAYS redirect after a successful POST:
Without seeing your code, you'll need a redirect like this:
if($inserted){
header('Location: mypage.php?msg=reg_success');
exit;
}
Then, on mypage.php, you could so something like:
if(isset($_GET['msg'])){
switch($_GET['msg']){
case 'reg_success':
echo 'Registration successful!';
break;
}
}
Or, you could create an array for success messages:
$success_messages = array(
'reg_success' => 'Registration successful!',
'logout_success' => 'Logged out!'
);
And then on mypage.php:
if(isset($_GET['msg']) && array_key_exists($_GET['msg'], $success_messages)){
$msg_index = $_GET['msg'];
echo $success_messages[$msg_index];
}
You should record all registration data in session and write them once after user click some "Finish" button.
Then redirect him and clear relavant session data.
By this way you can have any number of stage pages and nothing will be duplicated.

Unset POST values in php

acitvity.php
//Form start
<form action=''>
</form>
//Form End
//Get POST Values
<?php
$_POST[''];
?>
//End
if i refresh the page after form is submitted, all the posted values are resubmitted, reason because all values are in browser so they are resubmitted. When i was searching solution for this, i got info that if the form & post operation done in separate php file then no more issue in posting values on refresh.
Is this the solutions? but now i have to do both in single file & POST values should not be submitted again on refresh.. is there any way to do this???
Learn PRG Pattern so that you can do this properly :)
http://en.wikipedia.org/wiki/Post/Redirect/Get
For example, you are trying to handle a user registration form, so what you do is you get a bunch of POSTed values, and save it into your database.
if(!empty($_POST)) {
// validate and save to db
// get last inserted user_id
}
After you do that, instead of returning the same page with the previously POSTed values, you redirect the new user, for example to his profile page (assuming you have no activation requirement in place)
if(!empty($_POST)) {
// validate and save to db
// get last inserted user_id, say in $user_id
header("Location: /users/$user_id");
}
That way, the browser redirects and you won't have problem with say, double registration, whenever the user hits refresh.
After saving to your database, reload your page:
if ($_POST) {
// Save $_POST to database and other stuffs
// Reload current page to discard $_POST
header('Location: my_page.php');
}
That's called PRG or Post/Reload/Get
You can use unset($var) to unset a variable. However, I think the issue is with the browsers; some of them try to be smart and will remember form data regardless when you refresh the page. If you hit "go" or "enter" on the URL bar it does a "true" refresh though.

Categories