Using the code below, I'm having trouble with showing form responses on submit. I've tried a mix of _GET and _POST, but I don't understand what to use and when because I'm relatively new to PHP. How could the code show form responses on submit?
<?php {
$fDogErr = $lDogErr = "";
// only show the information if the button named "subButton" has been pressed
if (!isset($_POST['submit'])) {
// set the variable with the submitted value
if (empty($fDog = $_POST['favourite dog'])) {
$fDogErr = "Need favourite dog";
} else {
$fDog = $_POST['favourite dog'];
}
if (empty ($lDog = $_POST['least favourite dog'])) {
$lDogErr = "Need least favourite dog";
} else {
$lDog = $_POST['least favourite dog'];
}
if (empty($password = $_POST['pawsword'])) {
$password = "";
} else {
$password = $_POST['password'];
}
if (empty($dogcac = $_POST['dogcac'])) {
$dogcac = "";
} else {
$dogcac = $_POST['dogcac'];
}
$secretdoggo = $_POST['secretdoggo'];
}
// display the user inputs to the screen
echo "<p>Your favourite dog is <b>" . $fDog . "</b>.</p>";
echo "<p>Your least favourite dog is <b>" . $lDog . "</b>.</p>";
echo "<p>Your pawsword is <b>" . $password . "</b>.</p>";
echo "<p> Did you know? <b>" . $secretdoggo . "</b>.</p>";
}
?>
You need to have an HTML form with all the input tags defined first. The form tag has an action attribute that states where the data will be sent (the PHP you linked), a method (POST, GET etc..) and a button with type submit that triggers the sending of the form data. The PHP file can then show your form responses when the submit button is clicked.
See the example below:
Form HTML Example:
<form method="post" action="response.php">
<label>Password:</label> <input type="text" id="favourite_dog" name="favourite_dog" />
<label>Password:</label> <input type="password" id="password" name="password" />
more input tags . . .
<button type="submit">Submit</button>
</form>
PHP Example Showing Responses:
response.php
<?php
if (!empty($_POST)){
$favourite_dog = $_POST['favourite_dog'];
$password= $_POST['password'];
echo "<p>Your favourite dog is <b>" . $favourite_dog . "</b>.</p>";
}
Hope this helps.
Related
I have this simple php code that generate a random code and display it to the user. I need to verify using a text input if the user insert the displayed code, like a captcha, but i will use this script to redirect the user after the verification,to the registration form page. The code is generated, but i can't verify it, maybe i've missed something in the code?
NB: This is not a spam prevention system. As said in the comments, there are valid solution better than this to prevent spam. This is a starting draft for an user invitation system, if you want to downvote the question please consider this.
<?php
function randomCode() {
$code_variable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
srand((double)microtime() * 1000000);
$i = 0;
$rand_Code = '';
while ($i <= 7)
{
$num = rand() % 33;
$tmp = substr($code_variable, $num, 1);
$rand_Code = $rand_Code . $tmp;
$i++;
}
return $rand_Code;
}
$code = randomCode();
if(isset ($_POST['verify'])){
if($_POST['user_code'] == $code ){
echo 'Valid code.';
header('Location: index.php');
}
}
?>
<form method="post" action="">
<input type="text" name="verification_code" disabled value="<? echo $code;?>">
<input type="text" name="user_code">
<button type="submit" name="verify">Verify code</button>
</form>
You will never get Valid code. being displayed on the screen since every time user clicks on Verify code button, the page will refresh and a new random captcha code will get generated and stored in $code. So that's why $_POST['user_code'] will never be equal to $code.
One workaround would be to append the captcha code in the URL itself, so that you could verify the authenticity of user-inputted captcha by comparing it with $_GET[...] data. So you need to change your form in the following way,
<form method="post" action="?captcha=<?php echo $code; ?>">
<input type="text" name="verification_code" disabled value="<?php echo $code;?>">
<input type="text" name="user_code">
<button type="submit" name="verify">Verify code</button>
</form>
Subsequently, verify captcha in the following way,
// your code
if(isset ($_POST['verify'])){
if($_POST['user_code'] == $_GET['captcha'] ){
// your code
}
}
Sidenote(s):
Don't output anything before the header(...); statement, otherwise you would see headers already sent error. Go through this SO thread to get more info on this.
header(...); alone is not sufficient to redirect the user to a different page, use exit(); after header(...); statement.
I've added the php mail() function to send the invitation code to users. It's working fine, i've divided the code into two parts. the first one manage the user invitation code sending:
<form method="post" action="?invitation=<?php echo $code; ?>">
<label for="email">Email</label>
<input type="text" name="email">
<button type="submit" name="send_invitation">Send invitation code</button>
</form>
<?php
session_start();
ob_start();
if(isset($_POST['send_invitation'])){
function randomCode()
{
$code_variable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
srand((double)microtime() * 1000000);
$i = 0;
$rand_Code = '';
while ($i <= 7)
{
$num = rand() % 33;
$tmp = substr($code_variable, $num, 1);
$rand_Code = $rand_Code . $tmp;
$i++;
}
return $rand_Code;
}
$_SESSION['code'] = randomCode();
$_SESSION['tmp_mail'] = $_POST['email'];
if(isset($_POST['verify'])){
$to = $_POST['email']; // this is your Email address
$from = "noreply#domain.com"; // this is the sender's Email address
$subject = "Affiliate invitation code";
$message = $_SESSION['code'] . " " . " is your invitation code.";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
}
?>
The second part of the script is on another page and manage the check for the code matching between stored code into the $_SESSION['code'] variable and the user input
<?php
session_start();
ob_start();
function redirect(){
header('refresh:3; url=affiliate/index.php');
exit;
}
if(isset($_POST['verify'])){
if($_POST['user_code'] == $_SESSION['code']){
echo "Valid invitation code. You can now register using $_SESSION['tmp_mail'] email address.";
} else { echo "Wrong code. Please enter a valid code or request a new one."; }
?>
<form method="post" action="?invitation=<?php echo $code; ?>">
<label for="Code">Invitation Code</label>
<input type="text" name="user_code">
<button type="submit" name="verify">Send invitation code</button>
</form>
Thanks in advance for your help. I am new to PHP. I have done a lot of learning to get to this point, but I am currently stuck.
I have a form with a 'fields-section' and a 'proof-section' that has 3 buttons - proof, edit and send. Initially, the 'fields-section' is displayed and the 'proof-section' is hidden. Of the 3 buttons, the 'proof' button is visible while the other 2 are not. After the form is completed and 'proof' is clicked, the fields are validated, some fields are transformed into Hebrew and a proof is presented to the user by hiding the 'fields-section' and showing the 'proof-section'. Here the 'edit' and 'send' buttons are available and the 'proof' button is hidden. I am integrating this form within a Wordpress page template.
I am finding that the PHP variables do not have any value and I don't understand why.
If I change echo htmlspecialchars($line1); to
if(isset($_POST['line1'])){
echo htmlspecialchars($_POST['line1']);
}
It works...but this solution doesn't work for $line1_hebrew because this is a calculated field. I deleted unnecessary code below to keep it short.
Below is my code from the Wordpress template:
<?php
include "hebrew-memorial-creator.php";
add_action( 'genesis_after_loop', 'em_form');
/**
* Output the form to the page
*
*/
function em_form() {
?>
<div id="hebrew-memorial-creator">
<form name="hebrewMemorialForm" action="" method="POST">
<div id="field_section">
<div>
<label for="line1">Line 1: </label><input type="text" name="line1" id="line1" value="<? echo htmlspecialchars($line1);?>" size="50" maxlength=40 />
<input type="hidden" name="line1_hebrew" id="line1_hebrew" value="<?php htmlspecialchars($line1_hebrew);?>" />
</div>
.... deleted some fields here
</div><!--field-section-->
<input type="submit" id="proof_button" name= "proof_button" value="PROOF">
<input type="submit" id="edit_button" name="edit_button" value="EDIT">
<input type="submit" id="submit_button" name="submit_button" value="SEND">
<div id="proof_section">
<?php echo htmlspecialchars($proof);?>
</div><!--proof-section-->
</form>
</div><!--hebrew-memorial-creator-->
<?php
} // end function em_form
genesis();
?>
Below is my code from hebrew-memorial-creator.php:
<?php
if (isset($_POST['line1'])) { $line1 = $_POST['line1']; }
... deleted code for other fields...
if(isset($_POST['proof_button'])) {
$formerrors = false;
// validate fields
// email address is required
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'email error';
$emailErr = 'Please enter a valid email address';
$formerrors = true;
}
if (! ($formerrors)) {
// for line1 - line4, create line1_hebrew - line4_hebrew - converting lowercase letters to Hebrew characters
// and write to hidden form fields
$line1_hebrew = convert($line1);
... deleted code for additional fields
// all fields validated
// show proof fields and submit/proof buttons
$proof = '<div class="bronze"><p style="font-size: 36px; text-align:center;">HERE IS YOUR PROOF :</p>';
$proof .= '<p>Line1: ' . htmlspecialchars($line1) . ' ==> ' . htmlspecialchars($line1_hebrew) . '</p>';
... deleted code for other fields
$proof .= '</div>';
$proof .= "<script>
$('#field_section').hide();
$('#proof_section').show();
$('#proof_button').hide();
$('#edit_button').show();
$('#submit_button').show();
$('html,body').scrollTop(0);
</script>";
` // curious if anyone has a better solution to hiding/showing field`
} // end if no errors
return;
} // end proof button pressed
if (isset($_POST['submit_button'])) {
....deleted formatting of mail variables
mail( $to, $subject, $message, $headers );
wp_redirect( get_site_url() . '/thank-you');
} // end send button pressed
// replacing any lowercase characters with their hebrew character equivalent
function convert($line) {
if (($line == '') || ($line == ' ')) {
return $line;
}
$newLine = "";
for ($i=0; $i < strlen($line); $i++) {
//$character = substr($line, $i, 1);
$character = $line[$i];
... deleted code
} // end for
return $newLine;
} // end function convert
?>
well im working on a small html form.
<form class="contact" action="" method="POST">
<label>Name : </label><input type="text" name="name" value="<? echo $name; ?>"/>
<p class="middle"><label>Comment : </label><textarea name="message"></textarea><? echo $message; ?></p>
<label class="captcha"><img src="captcha.php" style="line-height: 30px;"></label><input type="text" name="code"/>
<input type="submit" class="csubmit" value="Now !" name="get"/>
</form>
and this is the php code:
<?php
if (isset($_POST['get'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "no name. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "no message <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "wrong captcha <br />";
}
if (!empty($error)) {
echo '<p class="error">Error :<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
if (empty($error)) {
$message = mysql_real_escape_string($message);
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($_GET['id']);
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')");
echo "thank you";
}
}
?>
As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?
You can use .reset() on your form.
$("#form")[0].reset();
You could follow that with Javascript too
document.getElementById('form').reset();
Or, if successful, redirect the user back to your contact page:
header("Location: contact.php"); // redirect back to your contact form
exit;
EDIT
<input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" />
function clearform()
{
document.getElementById("name").value=""; //don't forget to set the textbox ID
document.getElementById("message").value=""; //don't forget to set the textbox ID
document.getElementById("code").value=""; //don't forget to set the textbox ID
}
Also use:
required="required"
so people will be required to fill out the input fields :)
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.
This is what I did in a nutshell:
<?php
// define variables and initialize with empty values
//error variables
$agentNameErr = "";
//non-error variables
$agentemail = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["agentname"])) {
$agentNameErr = "Missing";
}
else {
$agentname = $_POST["agentname"];
}
}
// form
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input name="agentname" type="text" id="agentname" autocomplete="on" placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />
//only shows up if $agentNameErr is assigned the value of "Missing"
<span class="error"><?php echo $agentNameErr;?></span>
</form>
It checks if $agentname is erroneous (blank). If it's not blank, I don't know how to proceed. I want it to just automatically submit all the information without any additional user input to a review page so the user can see if the name was spelled correctly. And then they can do a final submission.
I don't know MySQL.
In normal english:
//user presses the submit button
if ($agentname has error)
stay on page and display errors
else
submit automatically to next page (order review page for visual checking)
What do I do to "submit automatically to next page"?
Use a php session.
if ($agentname has error)
stay on page and display errors
else
{
$_SESSION['key1'] = 'something'
$_SESSION['key2'] = 'something else'
...
header('location: ' . $next_page);
}
If you don't know how to use php sessions see the examples here
Try this:
<?php
$agentNameErr = "";
$agentemail = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["agentname"])) {
$agentNameErr = "Missing";
} else {
$agentname = $_POST["agentname"];
header("Location: nextpage.php?agent=".$agentname);
}
} else {
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input name="agentname" type="text" id="agentname" autocomplete="on" placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />
//only shows up if $agentNameErr is assigned the value of "Missing"
<?php if(!empty($agentNameErr)) { ?>
<span class="error"><?php echo $agentNameErr;?></span>
<?php } ?>
</form>
<?php } ?>
Keep it simple. Capture the entire contents of the form and store in a session variable.
$agentNameErr = '';
$agentemail = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['agentname'])) {
$agentNameErr = 'Missing';
} else {
$_SESSION['agent-form'] = $_POST;
// Move to next page
header('Location: nextpage.php');
exit;
}
}
Once forwarded to the next page you can access the form data from the session variable.
// Entire contents of form
print_r($_SESSION['agent-form']);
// "agentname" data
print_r($_SESSION['agent-form']['agentname']);
There is probably a simple solution for this but i'm not very proficient in php! Basically I want to submit a form and the user be returned with a thank you overlay image without refresh. I've managed to get this to work BUT now the form validating isn't working properly...
I need to make my overlay only appear after the form validating is successful, if it isn't successful I need to display the error instead of the thank you overlay...
I know I could use ajax for this form but I don't want to rely on javascript!
At the minute the validating is working, but the image is being overlayed on top of it...
This is php code:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter your name</li>";
}
if(empty($_POST['formTown']))
{
$errorMessage .= "<li>You forgot to enter your town</li>";
}
$varName = $_POST['formName'];
$varTown = $_POST['formTown'];
$varAge = $_POST['formAge'];
$varEmail = $_POST['formEmail'];
$varOne = $_POST['hidden-one'];
$varTwo = $_POST['hidden-two'];
$varThree = $_POST['hidden-three'];
$varFour = $_POST['hidden-four'];
$varFive = $_POST['hidden-five'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,"\n" . $varName . ", " . $varTown . ", " . $varAge . ", " . $varEmail . ", " . $varOne . $varTwo . $varThree . $varFour . $varFive);
fclose($fs);
}
}
?>
This is my html (with the php code):
<?php
if (isset($_POST['formSubmit'])) {
print "<div class=\"thank-you\"><a href='enter.php'><img src='images/thankyou-overlay.png'/></a></div>\n";
}
?>
<div id="mainContainer">
<p>Just complete your entry details below.</p>
<?php
if(!empty($errorMessage)) {
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" target="_self">
<div class="inputContainer">
<label class="text" name="name">Full Name:</label>
<input type="text" class="box" name="formName" value="<?=$varName;?>">
</div>
... more html inputs...
</form>
Whatever you are going to do, you have to use Javascript. You can choose AJAX either using an iframe where you direct your post to, and reading it in a javascript to check status of posting.
Edit:
Like this you can post it:
<form action="do_stuff.aspx" method="post" target="my_iframe">
<input type="submit" value="Do Stuff!" />
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
So after the post, you have to read status from this iframe, (in other words de HTML output from it).
First , i am having difficulty comprehending what you are trying to do : But still i can point out a few things that have better alternates ;
You should put this code
if($_POST['formSubmit'] == "Submit")
{
...
}
above the form for the functionality you want
and also the above if should have an else to show the form when there are errors.
like
else
{
---form---
}
try this and c if it helps