php form submit to itself not working - php

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

Related

Passing variables after form submit PHP [duplicate]

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'];
}
}

PHP not mailing any form data

[Edit - added a complete form snippet] In my html - I have a single checkbox - which looks like this:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet" />
<form class="contact-form row" id="feedbacks" method="POST" action="feedback.php">
<div class="col-xs-10 col-xs-offset-1">
<fieldset class="form-group">
<label for="full_name"></label>
<input type="text" class="form-control" placeholder="Your name and surname" name="full_name" id="full_name">
</fieldset>
<fieldset class="">
<label for="feedback_email"></label>
<input type="text" class="form-control" placeholder="Your Email address" name="feedback_email" id="feedback_email">
</fieldset>
<div class="checkbox">
<label class="c-input c-checkbox">
<input type="checkbox" name="subbed" id="subbed">
<span class="c-indicator"></span>
<span class="text-muted m-l-1">subscribe to <abbr class="msa"></abbr> notifcation service.</span>
</label>
</div>
<fieldset>
<label for="message"></label>
<textarea class="form-control" rows="9" placeholder="Your message here.." name="message" id="message"></textarea>
</fieldset>
<div class="row m-t-1">
<fieldset class="col-xs-4 col-xs-offset-4">
<button class="btn btn-primary btn-block btn-lg" name="submit" type="submit" id="send_feedback">Send <i class="ion-android-arrow-forward"></i>
</button>
</fieldset>
</div>
</div>
</form>
<input type="checkbox" name="subscribed" id="subscribed" value="sub_me">
In my PHP, I've created a variable $subscribe which links to the subscribed checkbox.
The PHP is supposed to send an email of "I would not like to recieve news emails" when the checkbox is left alone. To achieve this I have opted to use the following ternary inside the PHP form validation code:
[Edit - Supplying all the PHP]
<?php
$value = '';
$error = "";
$error_message = "";
$info = "";
if($_SERVER['REQUEST_METHOD'] == "POST"){
$subscribe = 'Would ' . (isset($_POST['subbed']) && $_POST['subscribed'] == 'sub_me' ? 'like to ' : 'not like to ') . 'receive news emails.';
$admin_email = "myemail_address#gmail.com";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <noreply#domain.ac.za>' . "\r\n";
$headers .= 'Reply-To: ' . $feedback_email . "\r\n";
'X-Mailer: PHP/' . phpversion();
$full_name = $_POST['full_name'];
$feedback_email = $_POST['feedback_email'];
$feedback = $_POST['message'];
$rep_message = "some thank you message to " . $full_name;
$message = 'another message which references ' . $subscribe;
$reply = 'some message consisting of ' . $full_name;
mail($admin_email,"Feedback",$message,$headers,"-fforwardguy#gmail.com");
mail($feedback_email,"Feedback",$reply,$headers);
}
?>
[Edit] The Problem is that the form is only acknowledged as having been sent, but no data is received along with it.
[After edit extra info - Could the following things be affecting the form submission?
`
There are 2 forms on the page in question.
Both forms are submitted via AJAX.
The first form functions as expected.
Two mail functions are being used in this single PHP file (handling only one form).
After taking taking a closer look - I have found that the email which gets sent contains none of the text entered into the form.
(The AJAX function works and the success functions are run.)
Try this:
$subscribe = 'Would ' . (isset($_POST['subscribed']) && $_POST['subscribed'] == 'sub_me' ? 'like to ' : 'not like to ') . 'receive news emails.';
Here I am checking if the $_POST variable is actually set and then we are doing a loose comparison check to see if sub_me is the submitted value.
You could also try leaving the value attribute blank on the form element, then just check if $_POST['subscribed'] is actually set by just using isset($_POST['subscribed']). If the checkbox is NOT checked, isset($_POST['subscribed']) will return false.
Ok - so after I noticed what the actual problem was - I found out that My AJAX function was collecting data from the wrong form.

I've Tried - Single Page html with php vs google formscontact form

I was ask by a client to use link their contact form to a google doc. I have a video that shows step by step what i did but when i am submitting the form there is a redirect to a page that is being worked on and there is no response sent to the form file. I will post the code for the code.:
<div class="col-md-9 col-xs-12 forma">
<!--<form id="form" action="MWSContact.php" method="POST" enctype="text/plain">-->
<!--
<fieldset>
<input type="text" class="col-md-6 col-xs-12 name" name='name' placeholder='Name *'/>
<input type="text" class="col-md-6 col-xs-12 Email" name='Email' placeholder='Email *'/>
<input type="text" class="col-md-12 col-xs-12 Subject" name='Subject' placeholder='Subject'/>
<textarea type="text" class="col-md-12 col-xs-12 Message" name='Message' placeholder='Message *'></textarea>
</fieldset>
<div class="cBtn col-xs-12">
<fieldset>
<input class="send" type="submit" value="Send" />
<input class="reset" type="reset" value="Reset" />
</fieldset>
</div> -->
<!-- </form>-->
</div>
<?
if (isset($_POST['email'])){
//Here is the email to info
$emial_to = 'email';
$email_subject = "MWS Contact";
$email_from = "Client";
//Error Code
function died ($error){
echo "We are sorry, but there were error (s) in your submitted form.";
echo "These errors appear below.<br/><br/>";
echo $error. "<br/><br/>";
echo "Please check your information again.<br/>";
die();
}
//Validation
if (!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['message']) ||
!isset($_POST['subject'])){
died ('We are sorry but there appears to be a probem with your form submitted.');
}
//values
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
$subject = $_POST['subject'];
//error messages
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp, $email)){
$error_message .= 'The Email address you entered does not appear to be valid. <br/>';
}
$string_exp = "/^[A-Za-z.'-]+$/";
if (!preg_match($string_exp, $name)){
$error_message .= 'The name you endtered does not appear to be valid. <br/>';
}
if (strlen($message) <2){
$error_message .= 'The comment you entered does not appear to be valid.<br/>';
}
if (strlen($email_message) >0){
died($error_message);
}
//Sanitize
$email_message = "Form Details Below\n\n";
function clean_string($string){
$bad = array("content-type", "bcc:", "to:", "cc:", "href");
return str_replace($bad," ", $string);
}
$email_message .="Name:" . clean_string($name) . "\n";
$email_message .="Email:" . clean_string($email) . "\n";
$email_message .="Subject:" . clean_string($subject) . "\n";
$email_message .="Message:" . clean_string($message) . "\n";
"\n";
//headers
$headers = 'From: ' .$email_From . "\r\n". 'Reply-To:' . $email. "\r\n" . 'X-Mailer: PHP/' .phpversion();
#mail ($email_to, $email_subject, $email_message, $headers);
}
?>
Thank you for contacting us. We will be in contact with you shortly.
google form
Look at the lettercase for all your POST arrays for your assignments and conditional statements:
$_POST['name']
$_POST['email']
$_POST['message']
$_POST['subject']
then in your form
<input type="text" class="col-md-6 col-xs-12 name" name='name' placeholder='Name *'/>
<input type="text" class="col-md-6 col-xs-12 Email" name='Email' placeholder='Email *'/>
<input type="text" class="col-md-12 col-xs-12 Subject" name='Subject' placeholder='Subject'/>
<textarea type="text" class="col-md-12 col-xs-12 Message" name='Message' placeholder='Message *'></textarea>
Lettercase must match. You have email in $_POST['email'] and then name='Email' for your input.
Nothing inside the if (isset($_POST['email'])){...} conditional statement will fire up for that reason, including all other POST arrays which will not populate.
Same thing for all others. POST arrays/variables are case-sensitive.
So change them all to match name='email' and do the rest for the others.
Also, remove enctype="text/plain" from the form tags, that will make your form fail also;
this is very important.
Remember to remove the <!-- and --> from your code. Those are HTML comments and nothing will show up on your screen, nor executed.
Make sure that short open tags are enabled. Otherwise, you will need to change <? to <?php.
Remove the # for #mail, it's an error suppressor.
Error reporting would have signaled "Undefined index Email...." and others while having it enabled.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
It doesn't seem like you're doing anything with $subject and there is nothing assigned for $email_to in regards to where it's being emailed to. You will need to modify your code as to what it should be.
$email_to = "email#example.com"; needs to be added in your code, replacing it with your email address.
Edit:
You have $emial_to = 'email'; that's a typo. See above code.
$email_From and $email_from = "Client"; more typos.
You should be using $email instead, and from $email = $_POST['email'];
mail() expects a From: to be an email and not a name.
$headers = 'From: ' .$email_From <= which should be $email.
...the edits seem to be next to endless.
Please go over your entire code and make sure that everything matches, no typos, letter-case issues. etc.
I believe I've given you more than enough to get you started.

How do I show a Bootstrap modal using PHP?

I don't think my title does this question justice but it may get confusing and I don't want to extend the title over several lines.
Here goes:
I have a single page website which has a contact form with the below code:
<form class="move-down" name="contactform" method="post" action="contact-form-handler.php">
<div class="controls controls-row">
<input id="name" name="name" type="text" class="span3" placeholder="Name">
<input id="email" name="email" type="email" class="span3" placeholder="Email address">
</div>
<div class="controls">
<textarea id="message" name="message" class="span6" placeholder="Your Message" rows="7"></textarea>
</div>
<div class="controls pull-right">
<button id="contact-submit" type="submit" class="btn btn-default">Send it!</button>
</div>
</form>
As you can see its action is to call an external php file called "contact-form-handler", which is shown below:
<?php
$errors = '';
$myemail = 'hello#wunderful.co.uk';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= die(header('Location: #errorModal'));
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= die(header('Location: #errorModal'));
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' modal
header('Location: #thanksModal');
}
?>
<?php
?>
This has been working fine but as my new site is one page I don't want separate pages loading, nor do I just want to echo black text on a white background.
So my question is - How do I show the Bootstrap Modal window when the submit button is clicked, with php code from inside the external file AND without the page reloading?
I hope it can be done. If it can't can someone help me launch a modal that says error or thanks when the submit button is clicked?
yes you can. Since you are not using oop way you can do this
1) on page submit you will assign some $mail_send = true; after email is send
2) you fill then say <?php if ($mail_send) { ?> code for modal here <?php } ?>
3) Drop this header('Location: #thanksModal'); you do not need that.
Put $mail_send = true; instead of that.
that is all.

Please advice why the form is not redirecting to the url?

Please help with this php contact form. It works, however, I want to redirect the visitor to a different .html page instead of showing a thankyou message, but i do not want to lose the contact form info. Thanks !
I am using very simple contact form:
<form method="POST" action="sendmail.php" class="form">
<p class="yourName"> Submit Name:</p>
<input name="text" class="name" placeholder="Name" name="name">
<p class="yourEmail">Submit Email:</p>
<input type="text" class="email" placeholder="Email" name="email">
<p class="yourInquiry">Submit Inquiry:</p>
<input type="submit" value="Submit" class="Button">
</form>
<?php
$to = "xyz#hotmail.com";
$subject = "Inquiry from ". $_POST['name'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$html`enter code here` = "";
foreach ($_POST as $name => $value) {
$html .= "<strong>$name</strong><br>";
$html .= "<p>$value</p><br>";
}
if (mail($to, $subject, $html,$headers)) {
/* Success Message */
} else {
/* Error message */
}
header('Location:about.html');
} else {
echo "You didnt enter anything";
?>
header and related functions (in particular setcookie) MUST appear before ANY content on the page. In this case, your form is sent before it.
You can either rearrange your code so that the form processing appears before the form, or start your code with ob_start to bypass the restriction (but this is only a good idea if you actually intend to pass a callback to the function)
You must not output (or echo) anything before using function header()
Put all your logic on the top of your script and html markup on the bottom, so you would be able to perform header('Location:about.html');
First if you want to redirect using header location you can't show any message like Success Message or Error Message.
Second use header("Location:about.html");
Try it change the order of your code as show below
<?php
if(isset($_POST["yourName"])){
$to = "xyz#hotmail.com";
$subject = "Inquiry from ". $_POST['name'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$html`enter code here` = "";
foreach ($_POST as $name => $value) {
$html .= "<strong>$name</strong><br>";
$html .= "<p>$value</p><br>";
}
if (mail($to, $subject, $html,$headers)) {
/* Success Message */
} else {
/* Error message */
}
header("Location:about.html");
} else {
echo "You didnt enter anything";
}
?>
<form method="POST" action="sendmail.php" class="form">
<p class="yourName"> Submit Name:</p>
<input name="text" class="name" placeholder="Name" name="name">
<p class="yourEmail">Submit Email:</p>
<input type="text" class="email" placeholder="Email" name="email">
<p class="yourInquiry">Submit Inquiry:</p>
<input type="submit" value="Submit" class="Button">
</form>
You cannot output anything before your header statement and you have to change your header() statement to:
header('Location: http://www.example.com/about.html');

Categories