Passing variables after form submit PHP [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
Is there an efficient way to pass variables from one page to another after form submission? I'm struggling to maintain the variables that are submitting on the form page to display them on the confirmation page after being redirected on submission.
Could it be the way i'm 'storing' the data with $_POST? Should I be using sessions? If I should how would I go about storing the $_POST in $_SESSION and being able to call it in the email template as a $variable-name format? Is using header(); to redirect inefficient in this manner and maybe redirecting via ajax? Not sure how I would approach that if so.
Form:
<form id="pricing-form-inquiry" action="<?php echo get_stylesheet_directory_uri(); ?>/pricing-form/form-handler.php" method="POST" role="form">
<div class="pricing-modal" id="modal1" data-animation="slideInOutLeft">
<div class="modal-dial">
<header class="modal-head">
<a class="close-modal" aria-label="close modal" data-close></a>
</header>
<section class="modal-body">
<div class="row">
<div class="col">
<input type="text" class="" placeholder="First Name" name="first-name" required data-error="First Name is required.">
</div>
<div class="col">
<input type="text" class="" placeholder="Last Name" name="last-name" required data-error="Last Name is required.">
</div>
</div>
<input type="email" class="" placeholder="Email Address" name="email" required data-error="Email Address is required.">
<input type="text" class="" placeholder="Company" name="company" id="company">
<input type="text" class="" placeholder="Phone Number" name="phone" id="phone">
<div class="row">
<div class="col text-center"></div>
</div>
</section>
<footer class="modal-foot">
<input type="submit" class="pricing-form-submit" value="Calculate" name="submit">
</footer>
</div>
</div>
</form>
form-handler.php
if(isset($_POST['submit'])) {
$first_name = filter_var($_POST['first-name'], FILTER_SANITIZE_STRING);
$last_name = filter_var($_POST['last-name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$company = filter_var($_POST['company'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$to = "email#email.com"; // Email Address to send lead to
$subject = "Subject Goes Here!"; // Subject of generated lead email
// HTML Message Starts here
$message = "<html><body><table style='width:600px;'><tbody>";
$message = "<tr><td style='width:150px'><strong>Name: </strong></td><td style='width:400px'>$first_name $last_name </td></tr>";
$message = "<tr><td style='width:150px'><strong>Email Address: </strong></td><td style='width:400px'>$email</td></tr>";
$message = "<tr><td style='width:150px'><strong>Company Name: </strong></td><td style='width:400px'>$company</td></tr>";
$message = "<tr><td style='width:150px'><strong>Phone Number: </strong></td><td style='width:400px'>$phone</td></tr>";
$message = "</tbody></table></body></html>";
// HTML Message Ends here
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: Company <from#email.com>' . "\r\n"; // User will get an email from this email address
// $headers .= 'Cc: from#email.com' . "\r\n"; // If you want add cc
if(mail($to,$subject,$message,$headers)){
// Message if mail has been sent
echo "<script>
alert('Mail has been sent Successfully.');
</script>";
header("Location: /pricing-confirm/");
} else {
// Message if mail has been not sent
echo "<script>
alert('EMAIL FAILED');
</script>";
}
}

To pass your variables onto the pricing-confirm page, you could pass the variables in your header() function like so
header("Location: /pricing-confirm.php?name=" . $first_name);
Once on your pricing-confirm.php page, you can grab the variables from the query string
if(isset($_GET['name']) {
$name = $_GET['name'];
}
If you want to pass multiple variables at once, you can either use & in the query string, or use urldecode with an array like this
$arr = [
"firstname" => $first_name,
"lasttname" => $last_name,
]
header("Location: /pricing-confirm.php?userdetails=" . urlencode(serialize($arr)));
If you have used serialize, you can get the values in the array like this
$queryArr = unserialize(urldecode($_GET['userdetails']));
you can then access them with their array key, like so
if(isset($_GET['userdetails']) {
$arr = $_GET['userdetails'];
if(isset($arr['firstname']) {
$firstName = $arr['firstname'];
}
}

Related

I have created a form, but posts are not coming

I have created a form, but posts are not coming. Form Code
<form method="post" action="contact.php">
<form class="quote">
<div>
<label>Name</label><br>
<input type="text" placeholder="Name">
</div>
<div>
<label>Email</label><br>
<input type="email" placeholder="Emial Address">
</div>
<div>
<label>Message</label><br>
<textarea placeholder="Message"></textarea>
</div>
<button class="button_1" type="submit">Send</button>
</form>
contact.php code
<?php $to = 'demo#spondonit.com'; $firstname = $_POST["fname"]; $email= $_POST["email"]; $text= $_POST["message"]; $headers = 'MIME-Version: 1.0' . "rn"; $headers .= "From: " . $email . "rn"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn"; $message ='<table style="width:100%"> <tr> <td>'.$firstname.' '.$laststname.'</td> </tr> <tr><td>Email: '.$email.'</td></tr> <tr><td>Email: '.$text.'</td></tr> </table>'; if (#mail($to, $email, $message, $headers)) { echo 'The message has been sent.'; }else{ echo 'failed'; } ?>
Maybe the route of the page is wrong, try:
action="/contact.php">
if it's on the same folder
You really need to provide more detail - what does it mean that posts are not coming? Do you see the "failed" message or nothing at all?
But, most importantly: you use identifiers such as $_POST['fname'] but there is nothing in your HTML indicating that a text input value should be sent as "fname". You need to add a name attribute to all of your <input>s, for example:
<input type="text" name="fname" placeholder="Name">
Neither placeholder= or <label> suffice - they only affect how the form is displayed on the webpage and not how it is sent to the server.

php form submit to itself not working

i have a html form that submit to it self here is the html form
<div class="col-md-6 contact-grid">
<form name="submitted" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<div class="styled-input wow slideInUp animated animated" data-wow-delay=".5s">
<input type="text" id="name" required />
<label>Name</label>
<span></span> </div>
<div class="styled-input wow slideInUp animated animated" data-wow-delay=".5s">
<input type="email" id="email" required />
<label>Email</label>
<span></span> </div>
<div class="styled-input wow slideInUp animated animated" data-wow-delay=".5s">
<input type="tel" id="phone" required />
<label>Phone</label>
<span></span> </div>
<div class="styled-input wide wow slideInUp animated animated" data-wow-delay=".5s">
<textarea id="message" required></textarea>
<label>Message</label>
<span></span> </div>
<div class="send wow shake animated animated" data-wow-delay=".5s">
<input name="submit" type="submit" value="Send">
</div>
</form>
</div>
and below is my php code to processes the form
<?php
session_start();
//error_reporting(0);
if(isset($_POST['submitted'])) {
$sendto = "info#davfubgroup.com";
$usermail = strip_tags($_POST['email']);
$content = nl2br($_POST['message']);
$phone = strip_tags($_POST['phone']);
$name = strip_tags($_POST['name']);
$subject = "New Feedback Message";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "<p><strong>Name:</strong> ".$name."</p>\r\n";
$msg .= "<p><strong>Phone:</strong> ".$phone."</p>\r\n";
$msg .= "</body></html>";
if(mail($sendto, $subject, $msg, $headers)) {
$_SESSION['errormsg'] = "Mail Sent. Thank you we will contact you shortly.";
echo '<center><p style="color:green">' . $_SESSION['errormsg']. '</p></center>';
} else {
$_SESSION['errormsg'] = "Mail not Sent. Try Again.";
echo '<center><p style="color:red">' . $_SESSION['errormsg'].
'</p></center>';
}
}
?>
but my problem is when the form is submitted no message is display and no error message too any help please
just change the name of the input to
<input name="submitted" type="submit" value="Send">
it will work
It doesn't work because you are asking if $_POST has a key named submitted but there's no input element with that name.
Instead, you can check if there is any data in $_POST by asking:
if (count($_POST) > 0)
Your check for post should be: strtoupper($_SERVER['REQUEST_METHOD']) === 'POST' instead of: isset($_POST['submitted']) . Don't use count($_POST) either because the user could post an empty form (perhaps form was just a checkbox that the user didn't check).
When you submit your form, each field will be available in $_POST but the name attribute on the form tag is not submitted and is totally ignored by PHP when you submit your form (not sure about that btw).
In the given example, $_POST will only contain a key submit because this is the only input element with a name attribute.
In your code, assuming you have submitted your form, $_POST['submitted'] is undefined so isset($_POST['submitted']) is never evaluated to true.
You also need to validate user input in PHP, the required attribute doesn't guarantee in any way the validity of data on the server side. You can -at least- check if fields are empty and/or if the provided email is valid with PHP's native function filter_var():
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false){
// The provided email is invalid
};
You should consider using <span style="text-align: center;"></span> instead of <center> which is not valid.
Hope it helps.
Whilst answered already, in your isset() you are using the name of the form, since the rest of your code can handle the actual usefulness of the data when using your initial isset() you should use the name assigned to your submit button, in this case that would be if(isset($_POST['submit']){}
with the rest of your code then inputted, this is one of those learn from mistakes, using the name of the whole form in this scenario will get you nowhere, refer to individual input elements of the form
Best of luck, hope this helps

Unable to replace form with message on submission

I've created an HTML5 form, which incorporates reCAPTCHA, and I've also written a PHP script that sends an email when the form is submitted. At the moment, the script redirects the user to an error or thankyou page, but I'm trying to adjust it to dynamically replace the form within a message within the same page.
I've tried the following script, but it displays the message as soon as the page loads, before any user interaction.
PHP/HTML:
<?php
if ($_POST) {
// Load reCAPTCHA library
include_once ("autoload.php");
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$emailFrom = $email;
$emailTo = "my#email.com";
$subject = "Contact Request";
// Prepare email body text
$body = "<strong>Name:</strong> $name <br /> <strong>Email:</strong> $email <br /> <strong>Message:</strong> $message";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: $name <$emailFrom>" . "\r\n";
$secret = 'XXX';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'],$_SERVER['REMOTE_ADDR']);
echo 'Your message was submitted!';
} else {
?>
<div class="contact-form">
<form role="form" method="post" action="index.php">
<label for="name"><span>Name</span><input type="text" class="input-field" name="name" required data-errormessage-value-missing="Please enter your name." /></label>
<label for="email"><span>Email</span><input type="email" class="input-field" name="email" required data-errormessage-value-missing="Please enter your email address." /></label>
<label for="message"><span>Message</span><textarea name="message" class="textarea-field" required data-errormessage-value-missing="Please enter your message."></textarea></label>
<label><span> </span><div id="recaptcha"><div class="g-recaptcha" data-sitekey="6LcBawsTAAAAAKBPfGs1jApXNRLvR2MIPng0Fxol"></div></div></label>
<label><span> </span><input type="submit" value="" class="submit-button" /></label>
</form>
</div>
<?php
}
?>
I'm new to PHP, so I'm not sure if it's a syntax or semantics issue. Any help would be greatly appreciated!
Here's one way of doing it.
Check to see if the form has been submitted with if(isset($_POST['submit'])). You can also use if($_SERVER['REQUEST_METHOD'] == 'POST') to see if the form has been submitted.
Then we check if the email has been successfully sent, and if it has we set the $success_message variable.
We then check to see if the $success_message variable is set, and if it isn't, we show the form.
Also, note that I added name="submit" to the submit button element. This is how we're checking to see if the form has been submitted.
I also changed stripslashes() to strip_tags() to prevent any malicious code from getting through.
<?php
// Load reCAPTCHA library
include_once ("autoload.php");
if(isset($_POST['submit'])) {
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = trim(strip_tags($_POST['message']));
$emailFrom = $email;
$emailTo = "my#email.com";
$subject = "Contact Request";
// Prepare email body text
$body = "<strong>Name:</strong> $name <br /> <strong>Email:</strong> $email <br /> <strong>Message:</strong> $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: $name <$emailFrom>" . "\r\n";
$secret = 'XXX';
$lang = 'en';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'],$_SERVER['REMOTE_ADDR']);
// EDIT: repositioned recaptcha from OP's PasteBin script, as requested and adjusted messaging
// changed $success var to $message and added error message
// Original if statement, which redirected the user
if($resp->isSuccess()){
// send the email
if(mail($emailFrom, $subject, $body, $headers)) {
// set the success message
$success_message = 'The form was sent! Yay!';
} else {
// error message
$error_message = 'Could not send email';
}
} else {
$error_message = 'Prove you are a human!';
}
}
?>
<div>
<!-- quick and dirty way to print messages -->
<?php if(isset($success_message)) { echo $success_message; } ?>
<?php if(isset($error_message)) { echo $error_message; } ?>
</div>
<?php if(!isset($success_message)): ?>
<div class="contact-form">
<form role="form" method="post" action="index.php">
<label for="name"><span>Name</span><input type="text" class="input-field" name="name" required data-errormessage-value-missing="Please enter your name." /></label>
<label for="email"><span>Email</span><input type="email" class="input-field" name="email" required data-errormessage-value-missing="Please enter your email address." /></label>
<label for="message"><span>Message</span><textarea name="message" class="textarea-field" required data-errormessage-value-missing="Please enter your message."></textarea></label>
<div class="g-recaptcha" data-sitekey="6LcBawsTAAAAAKBPfGs1jApXNRLvR2MIPng0Fxol"></div>
<script type="text/javascript"
src="https://www.google.com/recaptcha/api.js?hl=<?php echo $lang; ?>">
</script>
<label><span> </span><input type="submit" name="submit" value="" class="submit-button" /></label>
</form>
</div>
<?php endif; ?>

PHP Validation to require One of Two Form Fields filled in

I am developing a site that uses javascript to handle many functions and PHP based Captcha code to validate the form field.
It works great, but the form will submit if none of the fields are filled in.
I need one of two form fields ['email' or 'phone'] filled in, but neither can be left blank.
The error message can be the same error message thrown up when the captcha field is left blank or filled in incorrectly.
I am new to PHP code and cannot figure out for the life of me how to call the function.
The function code is:
<?php
if(isset($_POST['send'])){
$emailFrom = "clientemail.com";
$emailTo = "clientemail.com";
$subject = "Contact Form Submission";
$first_name = strip_tags($_POST['first_name']);
$last_name = strip_tags($_POST['last_name']);
$email = strip_tags($_POST['email']);
$phone = strip_tags($_POST['phone']);
$message = strip_tags(stripslashes($_POST['message']));
$body .= "First Name: ".$first_name."\n";
$body .= "Last Name: ".$last_name."\n";
$body .= "Email: ".$email."\n";
$body .= "Phone: ".$phone."\n";
$body .= "Comments: ".$message."\n";
$headers = "From: ".$emailFrom."\n";
$headers .= "Reply-To:".$email."\n";
if($_SESSION['security_code'] == $_POST['security_code']){
$success = mail($emailTo, $subject, $body, $headers);
if ($success){
echo '<p class="yay">Your e–mail has been sent.</p>';
}
} else {
echo '<p class="oops">Something went wrong. Hit the back button and try again.</p>';
}
} else {
?>
The form field:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" id="contact" name="contact">
<fieldset>
<label for="name"><span style="color:#bf252b;">*</span>First Name</label>
<input type="text" id="first_name" name="first_name" minlength="2"/>
<label for="name">Last Name</label>
<input type="text" id="last_name" name="last_name" minlength="2"/>
<label for="email"><span style="color:#bf252b;">*</span> Email</label>
<input type="text" id="email" name="email" />
<label for="phone"><span style="color:#bf252b;">*</span> Phone</label>
<input type="text" id="phone" name="phone" />
<label for="message">Message</label><div style="clear:both;"></div>
<textarea id="message" name="message" cols="40" rows="10" ></textarea>
<img src="../captcha.php" id="captcha" alt="captcha" style="padding:25px 0px 20px 0px;" />
<label for="security_code">Enter captcha</label>
<input type="text" id="security_code" name="security_code" autocomplete="off" class="required"/>
<button type="submit" id="send" name="send" style="margin:0px 0px 10px 12px;">Send!</button>
</fieldset>
</form>
<?php } ?>
There is a .php document for running captcha, but am I right in thinking there is a simple solution for this; some extra code in the existing code that will fix my issue? I really want to avoid javascript and plugins if I can help it.
Thanks in advance!!
Try this,
if($_SESSION['security_code'] == $_POST['security_code'] && (!empty($email) || !empty($phone))) {
instead of
if ($_SESSION['security_code'] == $_POST['security_code']) {
This is not convenient way to validate form but I hope this will help.
Add the required attribute to the fields you need required.
Fix your code!
Notice: Undefined variable: body in /../sendform.php on line 14
Do that:
$body = "First Name: ".$first_name."\n";
$body .= "Last Name: ".$last_name."\n";
$body .= "Email: ".$email."\n";
$body .= "Phone: ".$phone."\n";
$body .= "Comments: ".$message."\n";
Solution
if(($_SESSION['security_code'] == $_POST['security_code']) AND
(!empty($email) OR !empty($phone)) ) {
In other words:
Security code must be match
Email or Phone can not be empty

Having trouble with my contact form

I'm having a little trouble with my contact form. It's sending emails to my server but somehow it's not taking the information from the "email" field. Instead, what I get in the "From:" field is my address on the server like this: "muzedima#box693.bluehost.com".It's not taking the info from the "name" field either. What did I do wrong? Also, I'm trying to get the subject line to say the name of the sender, but I failed miserably, is it possible?
Here's the HTML:
<div class="large-7 medium-10 small-12 medium-centered large-centered column">
<div class="row">
<form method="post" action="email2.php">
<input type="text" name="name" class="defaultText" title="your name">
<input type="text" name="email" class="defaultText" title="your email address">
<textarea name="comments1" class="defaultText" title="Tell us about your business"></textarea>
<textarea name="comments2" class="defaultText" title="How can we help?"></textarea>
<div class="large-7 medium-10 small-12 medium-centered large-centered column">
<input type="submit" name="send message" value="Send Message">
</div>
</form>
</div>
</div>
And here's the PHP script:
<?php
if (isset($_POST['email']))
//if "email" is filled out, send email
{
//send email
$to = 'info#muzedimage.com';
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$subject = 'Inquiry from $name';
$comments1 = $_POST['comments1'] ;
$comments2 = $_POST['comments2'] ;
$message = $comments1 . "\n\n" . $comments2;
$headers = "From: $name, $email";
mail($to, $subject, $message, $headers);
echo "<script>window.location = 'http://www.muzedimage.com'</script>";
}
else
//if "email" is not filled out,
{
echo "Oops!, you forgot your email!";
}
?>
Thanks guys!
PHP variables are not evaluated inside of single quotes, only double quotes, therefore change the following:
$subject = 'Inquiry from $name';
//to
$subject = "Inquiry from $name";
Also for the email portion, you're not doing anything with it... so do something with it.
$message = $comments1 . "\n\n" . $comments2 . "\n\n" . $email;
Now it sends the email as well.
Ohgodwhy already pointed out one of the issues with your code, so I won't bother repeating it.
In regards as to why you're receiving the From: as "muzedima#box693.bluehost.com" is because of this line:
$headers = "From: $name, $email";
It needs to be like this:
$headers = "From: $name <$email>\r\n";
The $email variable must be encapsulated by < and > and it's best to end it with \r\n
Tested and working with both Ohgodwhy's answer and mine.

Categories