php post data in if else statement - php

I have a sign up form came with 3 pages.
I use jquery $post to post error message back without refresh
2nd php page will check all data. if all data correct than it will send to 3rd page(agreement page). If user click agree in 3rd page, than all data will write into database.
However I have problem to post data to 3rd page in php by using if & else
This is a sign up form. Therefor I can't use $_GET[]
ex. else{header("location:agreement.php?email=somedata&pw=somedata");}
is any way I can pass those data to 3rd page in php?
1st page
<form>
<input type="text" name="email"/>
(some input)...
<input type="button" onclick="get();"/>
</form>
JQUERY
function get(){
$('#error').hide();
$.post('signup.php',{firstname:signup.firstname.value,...},
function(output){$('#error').html(output).fadeIn(50);})
}
2nd page
signup.php
if(will check everything){echo "error";}
//Jquery will output error without refresh the page
else{
[Need to POST all sign up data from 1st page to 3rd page]
header("to agreement.php");
}
3rd page
agreement.php
if user tick agree. All sign up data will insert into database.

Why do you not store the data in the session? Then you can easily retrive it on page 3 without having it to pass to the client, then the server and back to the client again.

When You Add Data Then On First Form Add Data into Table and use record_id in session and on all other Form Pages Just Update That database Record

Store it in session or if you show pages store it in you can also use CURL but it's "hard" way to make it. With curl you can send POST with all variables you want to another page.

Example for sending email to 3rd php
function get(){
var email = $('#email').val();
$('#error').hide();
$.post('signup.php',{firstname:signup.firstname.value,email:email,...},
function(output){$('#error').html(output).fadeIn(50);})
}
signup.php
$email = $_GET['email'];
if(will check everything){echo "error";}
//Jquery will output error without refresh the page
else{
[Need to POST all sign up data from 1st page to 3rd page]
header("to agreement.php?".$email);
agreement.php
$email = $_POST['email'];
if user tick agree. All sign up data will insert into database.
}

Related

PHP Button to call function will cause function to be repeated if page refreshed

I have two simple HTML form buttons that call PHP functions to send emails now. Everything works fine except for one thing. If one of the buttons is clicked to send a report, and then the page is refreshed, the function seemed to be called again and the emails well go out again with a page refresh by a user using a browser refresh button.
If the page is refreshed, the email will go out again for the last button clicked. So, if I click on Button 1 and then refresh the page, I will get two reports for button 1. If I click on button #1, and then click on Button #2, only the second report will go out. If I click on button #2 and then #1, only Report #1 will go out again.
So, no matter how many buttons are clicked, refreshing the page will cause the last button click (only to repeat). Trying to unset the request parameter (in code below) has no effect all on the repeats caused by a page refresh.
I don't understand why (on a Page Refresh) the page is seeing the last button click made as set, and why the unset command is not working.
Thanks for any help.
if( isset( $_REQUEST['email_this_weeks_report'] )) {
unset($_REQUEST['email_last_weeks_report']);
#send email now email code for this week
}
if( isset( $_REQUEST['email_last_weeks_report'] )) {
unset($_REQUEST['email_last_weeks_report']);
#send email now email code for last week
}
<form>
<input class="ui-button ui-widget ui-corner-all" type="submit"
name="email_this_weeks_report" value="Email This Weeks Report Now" />
</form>
<form>
<input class="ui-button ui-widget ui-corner-all" type="submit"
name="email_last_weeks_report" value="Email Last Weeks Report Now" />
</form>
Clicking the button submits the form.
The data in the form is bundled up and included in the request.
Aside: You're using method=GET, the default, but you're not making a "safe" request. You are doing something, not just getting information. You should use a POST request.
When you click refresh, you tell the browser to make the request again and display a new version of the page.
Since the request includes the query string which says "send a particular email", it sends that email again.
Unsetting values in $_REQUEST has no effect because when the browser makes a new request with the same data in it: $_REQUEST just gets filled up again.
You should deal with this by using the PRG pattern:
Submit the form using method=POST
Have your PHP script process the data in the form (i.e. send the email) then redirect to a different PHP script
Have the new PHP script display the result (in this case there is no result, its just the form, you could use a plain HTML document with no PHP in it).
Change
<form>
To
<form method='POST'>
A simple way to prevent multiple submissions is to add a random token to the form in a hidden input.
<input type='hidden' name='formtoken' value='<?= uniqueid() ?>'/>
Every time the page is fetched from the server, the value of this hidden variable will change. So on the server side, you can prevent the same form being resubmitted by checking whether a form with this unique ID has been submitted before.
session_start();
$sessionToken = $_SESSION['formtoken']? : null;
$currentToken = $_POST['formtoken']? : null;
// If no session token yet: form has never been submitted
if(!$sessionToken):
// save the current token in session so we'll recognize it next time
$_SESSION['formtoken'] = $currentToken;
/* ok to send the email */
// ElseIf current token was already used: Duplicate form submission
elseif($sessionToken === $currentToken):
/* don't send the email!*/
// Else session token exists, but current token is new: User fetched a new form from server
else:
// update the session token
$_SESSION['formtoken'] = $currentToken;
/* ok to send the email */
endif;
When the user refreshes, the browser will ask if she wants to re-submit the form. If she does, you will know because the current token and the session token will be the same. It's up to you to decide how to handle it.
Refreshing a page with a GET or a POST form will resubmit the data (albeit it will ask you first in the POST scenario, which you should use by the way).
Try redirecting the user after form submit
if( isset(...) ){
// Do your logic
header('Location: https://you_site.com/your-form-page?thank-you');
exit;
}
This must be done before anything else is outputted on the page.

verify entrance source in php

I have a link on the page that opens a contact form in a modal window.
How can I verify that the user clicked on the link to access the contact form, and did not go to the page directly. I don't want users or bots inadvertently browsing to that page.
Thanks in advance!
You can check for $_SERVER['X_HTTP_REQUESTED_WITH'] header, which will be xmlhttprequest whenever it's an ajax request
You can use the referral url (you can access this url in PHP using $_SERVER["HTTP_REFERER"]) but you can't rely on it. First because it can be changed using a very simple script and second because that field is not always filled.
Another method is to use session to store the last visited page and then check this in your contact page. Anyway this method will also fail if the user see another page before access to the contact form but the page which you want the users start with was already loaded.
You can send a variable with it like
Contact Me
and in the modal test weather it set or not
if(isset($_GET['co'])):
//show the form
else:
//redirect
endif;
or you can use jquery to select that link and sends a variable posted with it like
Contact Me
$('.contact').click(function(){
$.post( 'contact.php', { direct: 'no'},function()
{
//call modal from here
}
);
});
then test if direct = no
if($_POST['direct'] == 'no'):
//show the form
else:
//redirect
endif;
and the jquery solution is more reliable
Sorry I was wrong
Have a form with a hidden field that contains a token, and validate that token with the session on postback.

How to send $_POST content without submit bottun

I have form inputs to send to another page to check on and validate them, and in case of errors I have to redirect the user back to the page where he/she filled the form.
So I need to send the content of $_POST back to refill the inputs to avoid refilling them manually...
How can I do that??
Here are two options:
1) Have the PHP script redirect back to the page with the form, with the form values in the URL as GET variables. You can then use those to refill the form.
2) You can send a POST request via jQuery without requiring the user to leave the page. See here: http://api.jquery.com/jQuery.post/ . With this, you can check the user's input in the PHP script, and only redirect them if their input is valid. This saves you the trouble of refilling the form. You can use it like this:
$.post("myphpscript.php",
{ someData: someValue, someMoreData: anotherValue },
function(returnData) {
// do stuff here on return
});
In myphpscript.php you can get the post values as $_POST["someData"] and $_POST["someMoreData"]. The function is what happens when the PHP script returns, and returnData is what the PHP script echoed.
If I'm correct you want to check your POST-values and if they are invalid input, you want the user to be directed back to the original page and fill the input-fields with the POST-values.
<input type="text" value="<?php echo (isset($_POST["text"] ? $_POST["text"] : "") ?> />
This checks if the POST-var is set, if so, it sets the value of the input-field to the value of the POST-var, else it sets the value to empty
An alternative to excellent answers posted is to store these values into the session and access them from there.

Retaining data in HTML form

I have an HTML form. Let's say I fill out all the fields and submit it (PHP script runs here).
Then I want to go back to the form using "Back" button of my browser.
What I see is the empty form.
What do I do to have the entered data retain on the page after I come back to it using "Back" button of the browser?
Thank you!
If you use the "Back" button of your browser then your browser is responsible for re-populating your form data.
Usually that functionality is handled by the browser, however if you want to "force" the fields to always be pre-filled with the user's data, you can store the $_POST data in a session variable and use that to load the form.
Example:
// submission page
session_start();
if(isset($_POST)){
// save the posted data in the session
$_SESSION["POST"] = $_POST;
}
Then on the actual form page, you can check to see if session data exists. It won't if the form is being loaded the first time, but it will if the user submits the form and then presses the browser back button:
// form page
session_start();
if(isset($_SESSION["POST"])){
// previous POST data has been saved
// build the form with pre-defined values from $_SESSION
...
} else {
// no previous data
// build the form without pre-defined values
...
}
Note that you must call session_start() before outputting any HTML.
Store the value in a session
session_start();
//form so that you have all the potential forms in a single session array
//form_1 to identify the form in question
if(!empty($_POST)){
$_SESSION['forms']['form_1'] = $_POST;//if this is for the public internet, then I would really consider making sure that the posted data matches the received data... (and that its comming from YOUR form), which is way too long to post here...
}
then on the form page
<input name="flowers" value="<?php echo if(isset($_SESSION['forms']['forms_1']['flowers'])){ echo htmlspecialchars($_SESSION['forms']['forms_1']['flowers']);} ?>" />
obviously the above can be simplified, but for a example's sake it's better this way.
(make sure to clean out the old form data eventually)
You can potentially store the data in the session, and re-populate it back using PHP sessions. You should create a separate back button that takes you to the previous page.
Example:
Storing data:
$_SESSION['data'] = $_POST['item1'];
In the HTML Forms:
<input type="text" name="someinput" value="<?=$_SESSION['data']?>" />

PHP Multiform Validation and Redirection

I have buy.php with a form where you enter items, quantity, shipping data, etc.
When you click the Submit button, it posts back to buy.php ($_SERVER['PHP_SELF']) and does some data validation.
If there are fields missing or errors, they are highlighted. If everything is correct, I save the $_POST data in $_SESSION variables, then do a header('Location: check.php'), where I display the data so the buyer can check the info one last time before actually buying.
Now, if I'm in check.php and hit the Back button to buy.php so I can change stuff, the browser asks if I want to resend the POST data. I'm trying to avoid that.
Anyone have any good advice or good practices for PHP Multiform validation?
Also, if I had n pages for the user to fill, buy.php, buy2.php, ... buyn.php before check.php would the same ideas still hold?
You could do a redirect to buy.php after saving to the session object, which then does a server redirect to check.php, it would mean when the user clicks back, they're going back to the GET request not the POST request
Yes - I agree with above. I ALWAYS do a redir away from the last post, so clicking back bounces them back without that error OR re-submissions. it also avoids complications. u can always tag the redir link page with a ?m or &m (i.e.: page.php?m) and have this at top of page: (use elseif there after)
if (isset($_GET['m'])) {
echo 'order placed.';
}
else {
//...
}
You can have it all on one page too. Just name the submit buttons submit1, submit2, like: (bear in mind if you use an image for submits, it becomes $_POST['submit1_x'] :)
if (isset($_POST[submit1]) {
//validate + save session data from form1
//display form 2
} else if(isset($_POST[submit2])) {
//validate + save session data from form2
//display form 3
} else {
//display first form
//<input type="submit" name="submit1" value="Continue">
}

Categories