I have a simple form which submits on a different page but it doesnt here, keep saying you need to enter name and email
I have echoed name and email variables but still the same
<?php
if (isset($_POST['subs'])) {
$name=mysql_real_escape_string($_POST['name']);
$email=mysql_real_escape_string($_POST['email']);
if (empty($name) || empty($email)) {
echo"<div class='alert alert-danger'>Please enter both name and email address</div>";}
else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo"<div class='alert alert-danger'>Invalid email address, please enter a correct email address!</div>";
}
else {
$insert=mysql_query("INSERT INTO subs (first_name, email) VALUES ('$name','$email')");
if ($insert) {
echo"<div class='alert alert-success'>Thank you for subscribing wit us</div>";}
}
}
}
?>
<div class="subs-mobile">
<form class="form-inline" role="form" method="post" action="<?php $_PHP_SELF ?>">
<div class="form-group">
<input type="text" class="form-control border-radius-zero" id="exampleInputPassword2" placeholder="First Name" name="name">
</div>
<div class="form-group">
<input type="email" class="form-control border-radius-zero" id="exampleInputEmail2" placeholder="Email" name="email">
</div>
<button type="submit" class="btn btn-primary border-radius-zero" name="subs">Subscribe</button>
</form>
First of all you are saying that your page submits at different page..but in the form action action field you are using $_SERVER['PHP_SELF'] which means your submitted data will be sent on the same page..you can either change the action field to the desired page or paste the script from other file to the script where form is made..
Second thing, at the beginning of the script in the isset function check whether $_POST['name'] and $_POST['email'] are set or not..
<?php
if(isset($_POST['name'], $_POST['email']))
{
$name=mysql_real_escape_string($_POST['name']);
$email=mysql_real_escape_string($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo"<div class='alert alert-danger'>Invalid email address, please enter a correct email address!</div>";
else {
$insert=mysql_query("INSERT INTO subs (first_name, email) VALUES ('$name','$email')");
if ($insert) {echo"<div class='alert alert-success'>Thank you for subscribing wit us</div>";}
}
}
?>
<body>
<div class="subs-mobile">
<form class="form-inline" role="form" method="post" action="<?php $_PHP_SELF ?>">
<div class="form-group">
<input type="text" class="form-control border-radius-zero" id="exampleInputPassword2" placeholder="First Name" name="name">
</div>
<div class="form-group">
<input type="email" class="form-control border-radius-zero" id="exampleInputEmail2" placeholder="Email" name="email">
</div>
<button type="submit" class="btn btn-primary border-radius-zero" name="subs">Subscribe</button>
</form>
</body>
I hope now it will help you..and for more guide read this tutorial click here
Related
I have one PHP form with some fields and google ReCAPTCHA field and values store in the database table, But i want to make the google ReCAPTCHA field required.
Code here:
<?PHP
if(isset($_POST['submit']))
{
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
$user_id=$_SESSION['id'];
$sql="insert into contact (name,email,message,user_id,status)
values('$name','$email','$message','$user_id','1')";
$qex=mysql_query($sql);
if(!$qex)
{
die("Contact information is not Added".mysql_error());
}
$msgsec="Contact information is Added";
?>
form code:
<script src='https://www.google.com/recaptcha/api.js'></script>
<form id='contactus' method='post' >
<input type='hidden' name='submit' id='submit' value='1'/>
<label><h2>Your Name <strong style="color:red">*</strong></h2></label>
<input type="text" class="form-control" required name="name" id="name" placeholder="Please enter you'r name"/>
<label><h2>Your Email <strong style="color:red">*</strong></h2></label>
<input type="email" class="form-control" required name="email" id="email" placeholder="Please enter you'r email address"/>
<label><h2>Your Message <strong style="color:red">*</strong></h2></label>
<textarea class="form-control" required name="message" id="message" placeholder="Please type you'r message here"></textarea>
<br />
<div class='container'>
<div class="g-recaptcha" data-sitekey="6LevWB0UAAAAAEPIUh40HptW3PxfYFqjvz2Wa05D"></div>
</div>
<div class='container'>
<input type="submit" name="submit" class="btn btn-primary" value="SEND MESSAGE">
</div>
</form>
as of now the Google ReCAPTCHA option is not required. the form details always stored with submit button wheather i click on captcha or not. i want to make Google ReCAPTCHA required. please check my code and let me know. what i am missing.
Thanks and Regards.
Ankit
Here is google captcha with validation
<html>
<script src='https://www.google.com/recaptcha/api.js'></script>
<?PHP
/*Site Key and secret key is different thing so change it with ur keys */
$errMsg ="";
if(isset($_POST['submit']))
{
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '*********************';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
print_r($responseData);
$name = !empty($_POST['name'])?$_POST['name']:'';
$email = !empty($_POST['email'])?$_POST['email']:'';
$message = !empty($_POST['message'])?$_POST['message']:'';
$user_id=$_SESSION['id'];
if($responseData->success):
//contact form submission code
$sql="insert into contact (name,email,message,user_id,status)
values('$name','$email','$message','$user_id','1')";
$qex=mysql_query($sql);
if(!$qex)
{
die("Contact information is not Added".mysql_error());
}
$errMsg="Contact information is Added";
else:
$errMsg = 'Robot verification failed, please try again.';
endif;
else:
$errMsg = 'Please click on the reCAPTCHA box.';
endif;
}
echo $errMsg ;
?>
<body>
<form id='contactus' method='post' >
<input type='hidden' name='submit' id='submit' value='1'/>
<label><h2>Your Name <strong style="color:red">*</strong></h2></label>
<input type="text" class="form-control" required name="name" id="name" placeholder="Please enter you'r name"/>
<label><h2>Your Email <strong style="color:red">*</strong></h2></label>
<input type="email" class="form-control" required name="email" id="email" placeholder="Please enter you'r email address"/>
<label><h2>Your Message <strong style="color:red">*</strong></h2></label>
<textarea class="form-control" required name="message" id="message" placeholder="Please type you'r message here"></textarea>
<br />
<div class='container'>
<div class="g-recaptcha" data-sitekey="*********************"></div>
</div>
<div class='container'>
<input type="submit" name="submit" class="btn btn-primary" value="SEND MESSAGE">
</div>
</form>
</body>
</html>
in your php file add this
if(isset($_POST['submit']))
{
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
$user_id=$_SESSION['id'];
$sql="insert into contact (name,email,message,user_id,status)
values('$name','$email','$message','$user_id','1')";
$qex=mysql_query($sql);
if(!$qex)
{
die("Contact information is not Added".mysql_error());
}
$msgsec="Contact information is Added";
}
else
{
//your message for select recaptcha or required
}
}
I have a Bootstrap form and after complete the form I want remain in the same page and display a thank you message just below the submit button.
Here my HTML code
<div id="form">
<div class="row">
<div class="col-md-12"><h3>RESTA IN CONTATTO</h3>
<form id="form_members" role="form" data-toggle="validator" novalidate action="form-data.php" method="POST">
<div class="form-group">
<label for="firstname" class="control-label">Nome</label>
<input type="text" class="form-control" name="firstname" id="name" placeholder="Inserisci il Nome" required>
</div>
<div class="form-group">
<label for="lastname" class="control-label">Cognome</label>
<input type="text" class="form-control" name="lastname" id="lastname" placeholder="Inserisci il Cognome" required>
</div>
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Enter the Email" data-error="Inserire email valida" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" id="terms" required data-error="Devi essere d'accordo con i termini di condizione d'uso">Privacy
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="submit" id="submit" onclick="this.form.clear()" value="submitmessage">Registrati</button>
</div>
</form>
<div id="submitmessage"></div>
and Here my php Code
<?php
$link = mysqli_connect("","","") or die("failed to connect to server !!");
mysqli_select_db($link,"");
if(isset($_POST['submit']))
{
$errorMessage = "";
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
// Validation will be added here
if ($errorMessage != "" ) {
echo "<p class='message'>" .$errorMessage. "</p>" ;
}
else{
//Inserting record in table using INSERT query
$insqDbtb="INSERT INTO `test`.`members`
(`firstname`, `lastname`, `email`) VALUES ('$firstname', '$lastname', '$email')";
mysqli_query($link,$insqDbtb) or die(mysqli_error($link));
}
}
?>
First check if your insert actually happen by assigning result to a variable, ie:
$res=mysqli_query($link,$insqDbtb);
Now, below your form you can add the following php code and you can use this variable in an if statement to echo different things:
if($_POST && $res)
{/*this code is executed if form is submitted and insert worked*/
echo ' <div class="alert alert-success" role="alert">
Grazie per esserti registrato!
</div>';
}
elseif ($_POST && !$res)
{ /*you can write a different message if insert did not happen*/
echo '<div class="alert alert-danger" role="alert">
<strong>Oh no!</strong> Provaci ancora
</div>';
}
Note that this might only work if you use php to process the form and scripts are on the same page so you would also need to modify your form like this:
<form action="register.php" method="post" accept-charset="utf-8">
(where register.php stands in for the name of your file)
and the submit button like this:
<input type="submit" name="submit" value="Submit" id="submit_button" class="btn btn-primary" />
Then at the top of your page, after you have set the parameters for the connection you put the following statement:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
and you can put all the form validation here. What happens is the first time you go to the file it will be through a GET so nothing happens, after you submit the form you access the same file but with a POST so the submission is validated.
To submit the form and stay on the same page you have two possibilites:
A) As other people have suggested you use Ajax
B) The other possibility which has the same visible result for the user is that when you submit your form you go back to the same page, so the user will see the same page but different things will be displayed depending on weather he has already submitted the form or not
To achieve this second solution you can do the following:
1)In your head you establish the connection (the php you have is improvable but as a first attempt should do the job)
2) In your page you put your form with the following modification:
<form action="FILNAME.php" method="post" accept-charset="utf-8">
and
<input type="submit" name="submit" value="Submit" id="submit" class="btn btn-default" />
THis way when a user clicks the button the form is submitted to the same page.
3) Now you need to check if your page is beening accessed for the first time (ie thoruh a GET) or after the form has been submitted, so where you want your message to appear you put the following if statement:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}
3) Within this bracket you put all your php to validate the form and after validation your insert command
$insqDbtb="INSERT INTO `test`.`members`(`firstname`, `lastname`, `email`) VALUES ('$firstname', '$lastname', '$email')";
$res = mysqli_query($link, $insqDbtb);
4) If the query created a new row you can write the thank you message:
if (mysqli_affected_rows($link) === 1) {echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! </p></div>';
If not you can write an alert instead
I learned this method from a book by Larry Ullman, you can find the scripts with examples for free
here
I am working on a registration system which comprises of 3 total steps.
Step 1 - user enters a username, system searches the database for the
username. IF the username is found, it checks the account status (ie:
no password created, complete but not verified, registered and
verified).
If user is not found, user is directed to Step 2.
If status = no password created, the user is directed to Step 3.
If status = complete but not verified / registered and verified, Display error message.
Step 2 - user enters personal details.
The page stores user inputs
Step 3 - user creates a password, the system connects to the database and INSERTs user info to the user table. A success message is
displayed.
I have managed to figure out and complete the coding for the first 2 steps, by displaying a new form when the previous form has been submitted.
Problem: However, I have just realised that I am unable to retrieve data from the previous form (ie: at step 3 I am unable to retrieve the Username from Step 1). I have tried using the 'header('location: ?user=$uname');' approach however this doest work because the URL gets reset when I submit the new form and I lose the username again. How do I create a proper multi-step form using ONLY PHP and how do I store the input values so I could use them at the last step. Below is my code:
<?php
include 'includes/session_info.php';
if(isset($_SESSION['user_id'])){
header('Location: index.php');
}
$errors = array();
if(empty($_POST['user_info']) === false){
require ('core/dbcon.php');
$usr_email = mysqli_real_escape_string($con, $_POST['email']);
$usr_joined = mysqli_real_escape_string($con, $_POST['joined']);
$usr_recruited = mysqli_real_escape_string($con, $_POST['recruited']);
if($usr_email){
//direct user to password form
}else{
$errors[] = 'Please complete all fields marked with a Red Asterisk.';
}
$form2 = $usr_email.'<br>'.$usr_joined.'<br>'.$usr_recruited;
}
if(empty($_POST['username_chck']) === false){
require ('core/dbcon.php');
$username = mysqli_real_escape_string($con, $_POST['uname']);
$rpt_uname = mysqli_real_escape_string($con, $_POST['r_uname']);
if($username && $rpt_uname){
if($username == $rpt_uname){
$query = mysqli_query($con, "SELECT status FROM users WHERE username = '$username'") or die(mysqli_error($con));
// Display registration form if Username is not found.
if(mysqli_num_rows($query) == 0){
$form1;
}
// Actions performed If username entered already exists in the database.
elseif(mysqli_num_rows($query) == 1){
$status = mysqli_fetch_assoc($query);
if($status['status'] == 0){
$errors[] = '<b>'.$username.'</b> is already registered and awaiting to be verified by our admins. Feel free to contact an Admin via the website or in-game to get verified.';
}elseif($status['status'] == 1){
//header("Location:?create_pwd&user=$username");
}elseif($status['status'] > 1){
$errors[] = '<b>'.$username.'</b> is already registered and verified by our Admins. Please log in to access you account.
If you have forgotten your password you can rest your password <a class="navbar-link error_link" id="intext-link" href="login.php?fp"><b>here</b></a>.';
}
}elseif(mysqli_num_rows($query) > 1){
$errors[] = 'An error has occurred. Looks like a there is more than one member with that username. Please contact the Administrator for assistance.';
}
}else{
$errors[] = 'Please ensure that the username entered in both fields match.';
}
}else{
$errors[] = 'Please complete all required fields.';
}
}
?>
<html>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<?php
if(empty($_POST['username_chck']) === false){
if(empty ($errors) === false){
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Username: </label><br>
<input type="text" name="uname" class="form-control" placeholder="Please enter your Runescape username." id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" placeholder="Please re-enter your Runescape username." required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
<?php
}else{ echo $reg_uname;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Email: </label>
<input type="email" name="email" class="form-control" id="Email" <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<div class="form-group">
<label for="Joined">Date Joined: </label><br>
<small class="notice">If you do not remember the exact date please select the first day of the month and year you joined (eg: 01/02/2001).</small><br>
<input type="date" name="joined" class="form-control" id="Joined" <?php if (isset($_POST['joined'])=== true){echo 'value="', strip_tags($_POST['joined']),'"';}?>>
</div>
<div class="form-group">
<label for="recruited">Recruited by: </label>
<select name="recruited" class="form-control" id="recruited">
<option value="" selected disabled>Select a Member</option>
<?php
require ('core/dbcon.php');
$usr_qry = mysqli_query($con, "SELECT user_id, username FROM users")or die(mysqli_error($con));
while($usr = mysqli_fetch_array($usr_qry)){
echo '<option value="'.$usr['user_id'].'">'.$usr['username'].'</option>';
}
?>
</select>
</div>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
</form>
<?php
}
}elseif(empty($_POST['user_info']) === false){
if(empty ($errors) === false){
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Email: </label>
<input type="email" name="email" class="form-control" id="Email" <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<div class="form-group">
<label for="Joined">Date Joined: </label><br>
<small class="notice">If you do not remember the exact date please select the first day of the month and year you joined (eg: 01/02/2001).</small><br>
<input type="date" name="joined" class="form-control" id="Joined" <?php if (isset($_POST['joined'])=== true){echo 'value="', strip_tags($_POST['joined']),'"';}?>>
</div>
<div class="form-group">
<label for="recruited">Recruited by: </label>
<select name="recruited" class="form-control" id="recruited">
<option value="" selected disabled>Select a Member</option>
<?php
require ('core/dbcon.php');
$usr_qry = mysqli_query($con, "SELECT user_id, username FROM users")or die(mysqli_error($con));
while($usr = mysqli_fetch_array($usr_qry)){
echo '<option value="'.$usr['user_id'].'">'.$usr['username'].'</option>';
}
?>
</select>
</div>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
</form>
<?php
}else
echo $reg_uname.'<br>'. $reg_email.'<br>'.$reg_joined.'<br>'.$reg_recruited.'<br>';
}else{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Username: </label><br>
<input type="text" name="uname" class="form-control" placeholder="Please enter your Runescape username." id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" placeholder="Please re-enter your Runescape username." required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
<?php
}
?>
</div>
</div>
</html>
Ps. I have looked into creating a session which gets destroyed when the user navigates away from the page Destroy PHP session on page leaving. However I find that it's not very user friendly as it doesn't work properly if the user has multiple tabs open. I understand that I need to implement a javascript function to make it work properly. I do not know how to code in javascript and would really appreciate your assistance on making a better multi-step registration process.
As mentioned above, store the POST data from each step in the session variable.
// Step 1 submit
$_SESSION['steps'][1] = $_POST;
// Step 2 submit
$_SESSION['steps'][2] = $_POST;
// Step 3 submit
$_SESSION['steps'][3] = $_POST;
You can then use something like currentStep in the session to determine where they last were.
$currentStep = $_POST['step'];
And compare to what data you need available, or just use it directly from the array.
I opted to follow the 'hidden variable' method where I store the values form the previous form in hidden inputs of the current form. Thus enabling me to pass the values on to the next form. A sort of snowball effect, if you will. Below is an example:
Form 1
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname">Username: </label><br>
<input type="text" name="uname" class="form-control" id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname">Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
Form 2
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email">Email: </label>
<input type="email" name="email" class="form-control" id="Email" required <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<input type="hidden" name="username" <?php if (isset($_POST['username'])=== true){echo 'value="', strip_tags($_POST['username']),'"';}else{echo "value=\"$username\"";}?>>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
Explanation
Below is a skeleton of my code which should help you understand how I have displayed the forms
if(empty($_POST['form1'])=== false){
$username = mysqli_real_escape_string($con, $_POST['username']);
// display form 2
}elseif(empty($_POST['form2'])=== false){
//display form 3
}
Note the hidden input type before the submit button in the second form.
While I have opted to include the if statements within the tags for the sake of this example, you could alternatively choose to process the forms at the top of your page (before the tag).
Newbie here, I found the problem when I tried to implement the code onto my website, which is made with bootstrap. I also made this weather scraper with bootstrap and php and that one ended up working under the default index.php ie. website.com
Code. Replaced my email with myEmail
PHP
<?php
if ($_POST["submit"]) {
if (!$_POST['name']) {
$error="<br />Please enter your name";
}
if (!$_POST['email']) {
$error.="<br />Please enter your email address";
}
if (!$_POST['comment']) {
$error.="<br />Please enter a comment";
}
if ($_POST['email']!="" AND !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.="<br />Please enter a valid email address";
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were errors(s) in your form:</strong>'.$error.' </div>';
} else {
if (mail("myEmail", "Comment from Website!", "Name: ".$_POST['name']."
Email: ".$_POST['email']."
Comment: ".$_POST['comment'])) {
$result='<div class="alert alert-success"><strong>Thank you!</strong>I\'ll be in touch.</div>';
} else {
$result='<div class="alert alert-danger"><strong>Sorry, there was an error
sending your message. Please try again.</strong></div>';
}
}
}
?>
HTML
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 emailForm">
<h1>Email Us</h1>
<?php echo $result; ?>
<p class="lead">Please get in touch, and we will get back to you asap.</p>
<form method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" placeholder="Name"
value="<?php echo $_POST['name']; ?>" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email" class="form-control" placeholder="Email"
value="<?php echo $_POST['email']; ?>" />
</div>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" name="comment" value="<?php echo $_POST['comment']; ?>"></textarea>
</div>
<input type="submit" name="submit" class="btn btn-success btn-lg" value="Submit" />
</form>
</div>
</div>
</div>
I cant see any obvious but try this:
<form method="post">
to
<form method="post" action="/index.php">
If the location of the PHP code is http://website.com/index.php
There's a lot of blank php email posts on here but none of them have solved this for me.
I tweaked this simple php code I found to simply email a specified email address (in this case, my client's email) with a feedback message from a customer on their website. Through testing, I could only get it to send emails when I didn't include the initial if statement as validation, but even then, the emails would have no subject or body.
contact.html
<form name="feedback" class="form-horizontal" role="form" action="send_form_email.php" method="post">
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="inputName" placeholder="Name"><br />
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" name="inputEmail" placeholder="Email"><br />
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-3 control-label">Message</label>
<div class="col-sm-9">
<textarea type="text" class="form-control" name="inputMessage" placeholder="Message"></textarea><br />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input class="btn btn-default" type="submit" value="Submit">
</div>
</div>
</form>
send_form_email.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Contact subject
$name =$_POST['inputName'];
// Details
$message=$_POST['inputMessage'];
// Mail of sender
$mail_from=$_POST['inputEmail'];
// From
$header="from: $name <$mail_from>";
// Enter your email address
$to ='test#gmail.com';
$send_contact=mail($to,$name,$message,$header);
// Check, if message sent to your email
// display message "We've recived your information"
header("Location: http://wetzelscontracting.com/postcontact.html");
if($send_contact){
echo "We've recived your contact information";
}
else {
echo "ERROR";
}}
?>
Ok guys, long story, but Mailto isn't actually in the action attr, I removed it from the post.
Actually, I don't know what kind of frankenstein code I originally posted, but that was full of errors that are no longer there. Hopefully I posted the right code this time.
Why is your form action MAILTO:?
<form name="feedback" class="form-horizontal" role="form" action="MAILTO:send_form_email.php" method="post">
It should just be a clean call to the PHP page like this:
<form name="feedback" class="form-horizontal" role="form" action="send_form_email.php" method="post">
The only time you would use MAILTO: is when constructing an <a href="mailto:someguy#someplace.somedomain">. For an HTML form using PHP like this the goal is to submit the form, and the the $_POST data gets parsed by the PHP which then acts on it to send an e-mail.
Additionally, you are not setting name values in any of the input fields & the names you have for id values dont even match what the PHP is attempting to do. So try this for the HTML:
<form name="feedback" class="form-horizontal" role="form" action="send_form_email.php" method="post">
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" placeholder="Name" name="inputName"><br />
</div></div>
<div class="form-group">
<label for="inputEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Email" name="inputEmail"><br />
</div></div>
<div class="form-group">
<label for="inputMessage" class="col-sm-3 control-label">Message</label>
<div class="col-sm-9">
<textarea type="text" class="form-control" id="inputMessage" placeholder="Message" name="inputMessage"></textarea><br />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input class="btn btn-default" type="submit" value="Submit">
</div></div>
</form>
Also here is the reworked PHP code.
The first thing I did was take all of your $_POST checks into a structure that uses one main array ($post_array) and then rolls through that array to process the values & assign them to similarly named variables. You had absolutely no input validation before. This is technically not even really great “validation” since isset() just checks to see if the $_POST value even exists. But this is step up.
Also I reworked your error checking logic at the end since it all happened after headers were sent. Meaning none of that the whole "We've recived your information" would never work. This is the best I can do with the info you’re providing, but I am doing this to convey the basic concepts:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST"){
// Set the post values array.
$post_array = array('inputName','inputEmail','inputMessage');
// Roll through the post values array.
foreach($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_key] ? $_POST[$post_key] : null;
}
// From
$header="from: $name <$mail_from>";
// Enter your email address
$to ='test#gmail.com';
$send_contact=mail($to,$name,$message,$header);
// Check, if message sent to your email
// display message "We've recived your information"
if($send_contact){
header("Location: http://wetzelscontracting.com/postcontact.html");
}
else {
echo "ERROR";
}
}
?>
As none of the other answers have covered the issue of validation apart from the one accepted, but if your going to do that you might as well just use the extract() function, (it also won’t protect from header injection or email validation).
It’s very important to validate user input and a layer of simple CSRF protection, else bots or spammers can directly POST to your PHP and it will send you a bombardment of emails, you won’t see the forest for the trees (legit emails), or worse inject headers into your inputEmail field and send their own emails using your server which is obviously something you don't want to happen.
Also I’ve added an easy way that you can pass errors from your PHP script that sends the user back to the form for you to echo out.
So for the send_form_email.php file.
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_SESSION['csrf'])){
//set error array to fill
$errors = array();
// Validate Contact subject
if(!empty($_POST['inputName'])){
$name = $_POST['inputName'];
}else{
$error['inputName'] = 'Required!';
}
// Validate Details
if(!empty($_POST['inputMessage'])){
$message = $_POST['inputMessage'];
}else{
$error['inputMessage'] = 'Required!';
}
// Validate Mail of sender
if(!empty($_POST['inputEmail'])){
if(filter_var($_POST['inputEmail'], FILTER_VALIDATE_EMAIL)){
$mail_from = $_POST['inputEmail'];
}else{
$error['inputEmail'] = 'Invalid Email!';
}
}else{
$error['inputEmail'] = 'Required!';
}
if(!isset($_POST['csrf']) || $_SESSION['csrf'] != $_POST['csrf']){
$_SESSION['email_status'] = 'Invalid csrf token!';
$error = true;
}
//stop multiple attempts - just remove csrf token
unset($_SESSION['csrf']);
//no errors send mail
if(empty($error)){
$headers ='MIME-Version: 1.0'."\r\n";
$headers.='Content-type: text/html; charset=utf8'."\r\n";
$headers.='From:<'.$mail_from.'>'."\r\n";
$headers.="X-Mailer: PHP"."\r\n";
if(mail('test#gmail.com', 'Website email form: '.$name, $message, $headers)){
$_SESSION['email_status'] = "We've received your contact information";
//send to success page
exit(header("Location: http://wetzelscontracting.com/postcontact.html"));
}else {
$_SESSION['email_status'] = 'There was an error sending the mail';
//backup to file
file_put_contents('mail.log.txt',print_r($_POST, true).PHP_EOL, FILE_APPEND);
}
}else{
//assuming its this url
exit(header("Location: http://wetzelscontracting.com/contact.php"));
$_SESSION['email_error'] = $error;
}
}else{
//stop multiple attempts
unset($_SESSION['csrf']);
//dont allow GET request/direct access
exit(header("Location: http://wetzelscontracting.com/contact.php"));
}
?>
Then in your page with the form, start a session to read from the $_SESSION array, and then echo out your errors if any.
<?php
session_start();
//make a session key that we will check against in send_form_email.php
$_SESSION['csrf'] = sha1(uniqid(true));
?>
<?php echo isset($_SESSION['email_status']) ? $_SESSION['email_status'] : null ?>
<form name="feedback" class="form-horizontal" role="form" action="send_form_email.php" method="post">
<input type="hidden" name="csrf" value="<?php echo $_SESSION['csrf'];?>"/>
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Name <?php echo isset($_SESSION['email_error']['inputName']) ? $_SESSION['email_error']['inputName'] : null?></label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" placeholder="Name" name="inputName"><br />
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-3 control-label">Email <?php echo isset($_SESSION['email_error']['inputEmail']) ? $_SESSION['email_error']['inputEmail'] : null?></label>
<div class="col-sm-9">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" name="inputEmail"><br />
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-3 control-label">Message <?php echo isset($_SESSION['email_error']['inputMessage']) ? $_SESSION['email_error']['inputMessage'] : null?></label>
<div class="col-sm-9">
<textarea type="text" class="form-control" id="inputMessage" placeholder="Message" name="inputMessage"></textarea><br />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input class="btn btn-default" type="submit" value="Submit">
</div>
</div>
</form>
<?php
//unset the errors so there only shown once
unset($_SESSION['email_status']);
unset($_SESSION['email_error']); ?>