php form submitted automatically - php

Hello I have a page index.php with a contact form in it, the problem is that when I load the page it's like I pressed the submit button and I don't know why.. I want that the alert of success or error only appear after pressing the submit button not any time the page load.. here is the code:
<?php
if($_POST["submit"]){//form was submitted
if($_POST['email'] != "" AND !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error .= '<br /><strong>Incorrect Email Address</strong>';
}
}else{
$result = '<div class="alert alert-danger"><strong>Form Not Submitted</strong></div>';
}
if($error)
$result .= '<div class="alert alert-danger"><strong>There was some error(s) in the form: </strong>'.$error.'</div>';
else {
if(mail("carlosd.dev#gmail.com",$_POST['subject'],"
Name: ".$_POST['name']."
Email: ".$_POST['email']."
Message: ".$_POST['message'])){
$result = '<div class="alert alert-success">Form Submitted We Will Be In Touch Soon!</div>';
}else{
$result = '<div class="alert alert-danger">Sorry the form was not submitted, please try again</div>';
}
}?>
and right above this I have my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>PHP | Practicas</title>
<meta charset="utf-8" />
<meta http-http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="styles.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="emailForm">
<h2>Contact Form<br /></h2>
<form action="index.php" method="post">
<div class="form-group">
<label for="name">Your name: </label>
<div class="input-group">
<input type="text" name="name" class="form-control" placeholder="Your Name" required="true" value="<?php echo $_POST['name']; ?>"/>
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
</div>
</div>
<div class="form-group">
<label for="email">Your email: </label>
<div class="input-group">
<input type="email" name="email" class="form-control" placeholder="Your Email" required="true"/>
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
</div>
</div>
<div class="form-group">
<label for="subject">Subject: </label>
<div class="input-group">
<input type="text" name="subject" class="form-control" placeholder="Subject of message" required="true" value="<?php echo $_POST['subject']; ?>"/>
<span class="input-group-addon"><span class="glyphicon glyphicon-tag"></span></span>
</div>
</div>
<div class="form-group">
<textarea name="message" class="form-control" placeholder="Enter the message" required="true"><?php echo $_POST['message']; ?></textarea>
</div>
<input type="submit" name="submit" class="btn btn-success btn-lg" value="Send!" />
</form>
</div>
</div>
</div>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</body>
</html>
</head>
what can I do to solve this??

Also check this
add to HTML form
<input type="hidden" name="submit" value="true">
PHP check if form submitted
<?php
if($_POST['submit']=='true') {
//true
} esle {
//false
}
?>
This will work for you

Your page is one self-calling element. What's happening is on first load it's trying to find the email and other inputs in $_POST array. Which naturally isn't there, hence the alert.
Use <form action='<?php echo $_SERVER['PHP_SELF']?>'' method="post"> instead of <form action="index.php" method="post">. This will most likely solve the problem.An off-topic suggestion: Use filter_input(INPUT_POST,'submit') instead of $_POST['index']. It's safer and is recommended.
Your Code seems to have lots of bugs when ran in my machine(WAMP Server). Initialize $error and $result variables. That seems to help.

put your PHP code on top and your HTML form on bottom
change this
if($_POST["submit"]){//form was submitted
with this
if(isset($_POST["submit"])){//form was submitted
also change this
if($_POST['email'] != "" AND !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
with this
if(!empty($_POST['email']) AND !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
also change the "error" check
if($error)
with
if(strlen($error)>0) {
and your else should be
{ else
ALL Code
<?php
if(isset($_POST["submit"])){//form was submitted
if(!empty($_POST['email']) AND !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error .= '<br /><strong>Incorrect Email Address</strong>';
}
} else {
$result = '<div class="alert alert-danger"><strong>Form Not Submitted</strong></div>';
}
if(strlen($error)>0) {
$result .= '<div class="alert alert-danger"><strong>There was some error(s) in the form: </strong>'.$error.'</div>';
} else {
if(mail("carlosd.dev#gmail.com",$_POST['subject'],"
Name: ".$_POST['name']."
Email: ".$_POST['email']."
Message: ".$_POST['message'])){
$result = '<div class="alert alert-success">Form Submitted We Will Be In Touch Soon!</div>';
} else {
$result = '<div class="alert alert-danger">Sorry the form was not submitted, please try again</div>';
}
}
?>

Use this isset()
if(isset($_POST['submit'])){
//here your code
}

Related

PHP Contact Form don't respond properly

I'm new to PHP and I've got issue in my contact form. When I press "Submit" in my form it skips (somewhere, I don't know where and why it happens) to other site, and conditions are not checked by the php code. What's more, you can type wrong answer in "human recognizer" and it will still send and email.
I was looking for som bad declarations or wrong syntax, but all seems to be good. I assume that also my contact.php responds properly if it sends an email (but without checking conditions).
I don't know if it's connected but my modal window in it also doesn't want to close (but on the other site the same code works fine, when there is other form withoud "action=contact.php" field).
My main head.php:
<!--HEAD-->
<head>
<title>X</title>
<!--META-->
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="SitePoint">
<!--CSS-->
<link id="theme" rel="stylesheet" href="css/light.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Font Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<!--END OF HEAD-->
<body>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script src="js/dropdown.js"></script>
<script src="js/scrolling-nav.js"></script>
<script src="js/theme-switch.js"></script>
<script src="js/nav-position.js"></script>
<nav id="mainNav">
<bar>
<i id="hamburger" class="fa fa-bars" aria-hidden="true"></i>
</bar>
<ul id="menu">
<li>Main</li>
<li>Generator</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
<section id = "main" >
<div class = "content">
<h1>Hello!</h1>
<p>:)</p>
</div></section>
<section id = "generator">
<div class = "content">
<h1>Generator</h1>
<form id="generator-form" ="form-horizontal" role="form" method="post" action="generator.php">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<label for="idCardNumber" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="idCardNumber" name="idCardNumber" placeholder="Student ID Card Number" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div></section>
<section id = "about">
<div class = "content">
<h1>About</h1>
<p></p>
</div></section>
<section id="contact">
<div class="content">
<h1>Contact</h1>
<p><a class="btn btn-default btn-lg" href="#contact-form">Contact Us</a></p>
<p><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5122.204450340393!2d19.91387757798398!3d50.065647167696376!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47165ba756b59b21%3A0xb20c8dba21b317d1!2sAkademia+G%C3%B3rniczo-Hutnicza+im.+Stanis%C5%82awa+Staszica+w+Krakowie!5e0!3m2!1spl!2spl!4v1511628584066" width="500rem" height="500rem" frameborder="0" style="border:0" allowfullscreen></iframe></p>
</div>
</section>
<footer>
<label class="switch">
<input type="checkbox" onchange=" switchTheme(this)">
<span class="slider"></span>
</label>
<p>Copyright©2017 for </p>
</footer>
<!--SIGN UP-->
<div id="contact-form" class="modal-window">
<div>
Close
<form action="contact.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<p class="text-danger"><?php echo $errName; ?></p>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<p class="text-danger"><?php echo $errEmail; ?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="4" name="message" value="<?php echo htmlspecialchars($_POST['message']);?>"></textarea>
<p class="text-danger"><?php echo $errMessage; ?></p>
</div>
<div class="form-group">
<label for="human">1 + 1 = ?</label>
<input type="text" class="form-control" id="human" name="human" pattern=".{1,}" required title="At least 1 character required" placeholder="Your Answer">
<p class="text-danger"><?php echo $errHuman; ?></p>
</div>
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary btn-lg"></input>
<div class="form-group">
<?php echo $result; ?>
</div>
</form>
</div>
</div>
<!--END SIGN UP-->
<!--CONTACT FORM-->
<div id="contact-form" class="modal-window">
<a title="Close" class="modal-close">Close</a>
<form id="contactForm" role="form" method="post" action="contact.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" pattern=".{3,}" required title="At least 3 characters required" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" pattern=".{3,}" required title="At least 3 characters required" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="4" pattern=".{3,}" required title="At least 3 characters required" name="message">
<?php echo htmlspecialchars($_POST['message']);?>
</textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
<div class="form-group">
<label for="human">1 + 1 = ?</label>
<input type="text" class="form-control" id="human" name="human" pattern=".{1,}" required title="At least 1 character required" placeholder="Your Answer">
<p class='text-danger'>$errHuman</p>
</div>
<input name="submit" type="submit" value="Send" class="btn btn-primary btn-lg">
<div class="form-group">
<?php echo $result; ?>
</div>
</form>
</div>
<!--CONTACT FORM-->
</body>
</html>
My contact.php code:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$human = intval($_POST['human']);
$from = 'Generator Contact';
$to = 'kamykx#gmail.com';
$subject = 'Message from AGH Generator Form';
$body ="From: $name\n E-Mail: $email\n Message:\n $message";
//CHECK NAME
if (!$name || empty($name)) {
$errName = 'Please enter your name';
}
//CHECK EMAIL
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
$errEmail = 'Please enter a valid email address';
}
//CHECK MESSAGE
if (!$message || empty($message)) {
$errMessage = 'Please enter your message';
}
//CHECK IF USER IS NOT A BOT
if ($human !== 2 || $human !=2) {
$errHuman = 'Please... proof that you are not a bot :>';
}
//SEND THE EMAIL IF THERE ARE NO EXISTING ERRORS
if (!empty($errName) && !empty($errEmail) && !empty($errMessage) && !empty($errHuman)) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! We will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
header("Location: home.php");
}
}
?>
EDIT:
I've done improvements in my php code (there was logical problem in line error fields are empty: was -> if(!empty($errName)) but should be -> if(empty($errName)).
But I've still got and issue. I've compressed the code in order to stay on the same page after contact form submit, but when we click the "submit" button nothing appears (no errors are displayed), page only refreshes and open the form again. What's wrong now? NEW CODE:
<!DOCTYPE HTML>
<html lang="en">
<!--HEAD-->
<head>
<title>AGH Application for entry with ECTS deficit generator</title>
<!--META-->
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="SitePoint">
<meta name="Description" content="It is simple PDF generator for sing with lack of ECTS for another term" />
<meta name="Keywords" content="ECTS, deficit, deficyt, Poland, Cracow, generator, application, form, pdf, AGH, UST, Akademia, Górniczko, Hutnicza, University, S cience, Technology, Polska, Kraków, " />
<!--CSS-->
<link id="theme" rel="stylesheet" href="css/dark.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Font Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<!--END OF HEAD-->
<body>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script src="js/dropdown.js"></script>
<script src="js/scrolling-nav.js"></script>
<script src="js/theme-switch.js"></script>
<script src="js/nav-position.js"></script>
<nav id="mainNav">
<bar>
<i id="hamburger" class="fa fa-bars" aria-hidden="true"></i>
</bar>
<ul id="menu">
<li>Main</li>
<li>Generator</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
<section id = "main" >
<div class = "content">
<h1>Hello!</h1>
<p>Welocome to The AGH Application for entry with ECTS deficit generator website. We hope that you use it just for fun :)</p>
</div></section>
<section id = "generator">
<div class = "content">
<h1>Generator</h1>
</div></section>
<section id = "about">
<div class = "content">
<h1>About</h1>
<p>This webapge was created as a project for the Web Technologies. The main reason why it exists is that very common among Students is that they want to apply for entry on another term with ECTS deficit. This site will help students and AGH employees by generating PDF application. We hope that everything at AGH will be fast and growing in the future. We want to make our students life BETTER! </p>
</div></section>
<section id="contact">
<div class="content">
<h1>Contact</h1>
<p><a class="btn btn-default btn-lg" href="#contact-form">Contact Us</a></p>
<?php echo $result; ?>
<p><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5122.204450340393!2d19.91387757798398!3d50.065647167696376!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47165ba756b59b21%3A0xb20c8dba21b317d1!2sAkademia+G%C3%B3rniczo-Hutnicza+im.+Stanis%C5%82awa+Staszica+w+Krakowie!5e0!3m2!1spl!2spl!4v1511628584066" width="500rem" height="500rem" frameborder="0" style="border:0" allowfullscreen></iframe></p>
</div>
</section>
<footer>
<label class="switch">
<input type="checkbox" onchange=" switchTheme(this)">
<span class="slider"></span>
</label>
<p>Copyright©2017 Marcin Kamiński for AGH </p>
</footer>
<!--SIGN UP-->
<?php
if (isset($_POST["send"])) {
$name = $_POST['name']; //Getting variable from form
$email = $_POST['email']; //Getting variable from form
$message = $_POST['message']; //Getting variable from form
$human = intval($_POST['human']); //Getting variable from form
$from = 'Generator Contact'; //Set sender
$to = 'kamykx#gmail.com'; //Where to send an email
$subject = 'Message from AGH Generator Form'; //Set the subject of email
$errName = $errEmail = $errMessage = $errHuman = ''; //Values of errors
$body ="From: $name\n E-Mail: $email\n Message:\n $message"; //Body of email
//CHECK NAME
if (empty($name)) {
$errName = 'Please enter your name';
}
//CHECK EMAIL
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
$errEmail = 'Please enter a valid email address';
}
//CHECK MESSAGE
if (empty($message)) {
$errMessage = 'Please enter your message';
}
//CHECK IF USER IS NOT A BOT
if ($human !== 2 || $human !=2) {
$errHuman = 'Please... proof that you are not a bot :>';
}
//SEND THE EMAIL IF THERE ARE NO EXISTING ERRORS
if (empty($errName) && empty($errEmail) && empty($errMessage) && empty($errHuman)) {
if (mail($to, $subject, $body, $from)) {
$result = '<div class="alert alert-success">Thank You! We will be in touch</div>';
}
else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
<div id="contact-form" class="modal-window">
<div>
Close
<form id="contactForm" role="form" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<p class="text-danger"><?php echo $errName; ?></p>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<p class="text-danger"><?php echo $errEmail; ?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="4" name="message" value="<?php echo htmlspecialchars($_POST['message']);?>"></textarea>
<p class="text-danger"><?php echo $errMessage; ?></p>
</div>
<div class="form-group">
<label for="human">1 + 1 = ?</label>
<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
<p class="text-danger"><?php echo $errHuman; ?></p>
</div>
<button id="send" name="send" type="submit" value="Send" class="btn btn-default btn-lg">Send</button>
</form>
</div>
</div>
<!--END SIGN UP-->
</body>
</html>
Your issue is in the logic of this line:
if (!empty($errName) && !empty($errEmail) && !empty($errMessage) && !empty($errHuman)) {
Basically this is saying if everything is wrong, send the email. The not empty check means that there was an error and the variable now holds the error string.
Instead, you just need to create the variables as an empty string and check if they are still empty:
$errName = $errEmail = $errMessage = $errHuman = '';
// CHECK NAME... etc... all the checks
if (empty($errName) && empty($errEmail) && empty($errMessage) && empty($errHuman)) {
However, you're not displaying the error to the user, and you're ending up with a bunch of loose variables. I recommend a slightly different approach using an array of errors...
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
$errors = [];
//CHECK NAME
if (!$name || empty($name)) {
$errors['name'] = 'Please enter your name';
}
//CHECK EMAIL
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
$errors['email'] = 'Please enter a valid email address';
}
//etc...
if (empty($errors)) {
//send email
} else {
$result = '<div class="alert alert-danger">Sorry there was an error sending your message:<br>';
foreach ($errors as $key => $error) {
$result .= $error . '<br>';
}
$result .= '</div>';
}
However, if you immediately call a header function after this, the user will never see the error or get a chance to fix it. You can use a query string to send errors back to head.php and display them.
(FYI, the action of a form sends all the POST data to that file, and if there is no action specified, then the form posts to itself.)

form validation using php not working in xampp

I am not able to validate the form using php and form is getting submitted even though its not validated. I am using Xampp sever. Please let me know the solution.
<?php
$error = "";
if($_POST) {
if(!$_POST["email"]) {
$error .= "Email address is required<br>";
}
if(!$_POST["subject"]) {
$error .= "Subject is required<br>";
}
if(!$_POST["exampleTextarea"]) {
$error .= "Text Area address is required<br>";
}
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
$error .= "Email address is invalid<br>";
}
if($error != ""){
$error = '<div class="alert alert-danger" role="alert"><p><strong>Oh snap! There were error(s) in your form:</strong></p>'. $error . '</div>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>
<body>
<div class="container"id="containerID">
<h1>Get in touch!!!</h1>
<div id="error"><? echo $error; ?></div>
<form method="post">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" name="email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject" name="subject">
</div>
<div class="form-group">
<label for="exampleTextarea">What would you like to ask us??</label>
<textarea class="form-control" id="exampleTextarea" rows="5" name="exampleTextarea"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script type="text/javascript">
</script>
</body>
</html>
Problem with your code not handling form post correctly, your are overriding the value for variable $error where you are checking
if ($error != "") {
$error = '<div class="alert alert-danger" role="alert"><p><strong>Oh snap! There were error(s) in your form:</strong></p>'. $error . '</div>';
} this will lead to neglect all the previous error assignment you have made above this piece of code. Plus on page reload the $error initializes with "", so all the hard work in validating errors and populating the $error variable becomes useless. Therefore, I have used session in my answer.
<?php
$error = "";
$errors = "";
session_start();
if(isset($_POST['submit'])) {
if(empty($_POST["email"])) {
$error .= "Email address is required<br>";
} else if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
$error .= "Email address is invalid<br>";
}
if(empty($_POST["subject"])) {
$error .= "Subject is required<br>";
}
if(empty($_POST["exampleTextarea"])) {
$error .= "Text Area address is required<br>";
}
if($error != ""){
$errors = '<div class="alert alert-danger" role="alert"><p><strong>Oh snap! There were error(s) in your form:</strong></p>'. $error . '</div>';
$_SESSION['errors'] = $errors;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>
<body>
<div class="container"id="containerID">
<h1>Get in touch!!!</h1>
<?php
if (isset($_SESSION['errors'])) {
echo $_SESSION['errors'];
unset($_SESSION['errors']);
}
?>
<form method="post">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" name="email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject" name="subject">
</div>
<div class="form-group">
<label for="exampleTextarea">What would you like to ask us??</label>
<textarea class="form-control" id="exampleTextarea" rows="5" name="exampleTextarea"></textarea>
</div>
<button type="submit" name="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script type="text/javascript">
</script>
</body>
</html>
Try giving your <button> a name, like <button name="submitbtn"> and at the top of the if statement, try if(isset($_POST['submitbtn'])
I don't know will this work in your code, but this is what I normally do.
Instead of
<div id="error"><? echo $error; ?></div>
try this
<div id="error">
<?php
echo $error;
?>
</div>

PHP value showing in HTML [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 7 years ago.
I'm having a pretty basic mistake here somewhere..
Trying to make this bootstrap form to work. I have two files: index.html, index.php and they're both in the same folder.
As you can see, the PHP content inside my HTML is showing, no clue why.
Im running it on Apache, but wait before you say that's the problem, I've tested it on another server (Linux) and it doesn't work either.
edit:
adding
AddType application/x-httpd-php5 .html .htm
AddHandler fcgid-script .html
FCGIWrapper /usr/local/cpanel/cgi-sys/php5 .html
AddHandler x-httpd-php5-cgi .html
to my .htaccess
and other combinations don't work....
Thank you.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Bootstrap contact form with PHP example by BootstrapBay.com.">
<meta name="author" content="BootstrapBay.com">
<title>Bootstrap Contact Form With PHP Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="page-header text-center">Contact Form Example</h1>
<form class="form-horizontal" role="form" method="post" action="index.php">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
<?php echo "<p class='text-danger'>$errHuman</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>
and my index.php:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$human = intval($_POST['human']);
$from = 'Demo Contact Form';
$to = 'example#domain.com';
$subject = 'Message from Contact Demo ';
$body ="From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
}
}
}
?>
What I see is this:
Another solution is to do away with the .html file and put everything in index.php, which will then be the default file to run when someone goes to to your url (most web servers with PHP installed will be configured to run index.php if there is no index.html).
Your php file would look something like this:
<?php
[your php code here]
?>
[your html code here]
But your php snippets must be in a PHP as a .html file won't be parsed by the PHP interpreter at all.

contact form error un defined

I am using the code below to send an email and attach an image with a short description.
I am getting the error below and I don't understand why:
Notice: Undefined index: name in C:\wamp\www\form\index.php on line 64 Call Stack #TimeMemoryFunctionLocation 10.0012146120{main}( )..\index.php:0 ">**
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$human = intval($_POST['human']);
$from = 'Demo Contact Form';
$to = 'example#domain.com';
$subject = 'Message from Contact Demo ';
$body ="From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">
Thank You! I will be in touch
</div>
'; } else { $result='
<div class="alert alert-danger">
Sorry there was an error sending your message. Please try again later.
</div>
'; } } } ?> <!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Bootstrap contact form with PHP example by BootstrapBay.com.">
<meta name="author" content="BootstrapBay.com">
<title>Bootstrap Contact Form With PHP Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="page-header text-center">Contact Form Example</h1>
<form class="form-horizontal" role="form" method="post" action="index.php">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_post['name']); ?>"> <?php echo "<p class='text-danger'>
$errName
</p>
";?>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php echo htmlspecialchars($_post['email']); ?>"> <?php echo "<p class='text-danger'>
$errEmail
</p>
";?>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?>
</textarea>
<?php echo "<p class='text-danger'>
$errMessage
</p>
";?>
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
<?php echo "<p class='text-danger'>
$errHuman
</p>
";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" type="submit" name="submit" value="submit" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
The error message explains exactly what the issue is. The name variable is not set when you first load the page, because nothing has been posted yet. So of course, $_POST['name'] does not exist. That's what the php error is telling you. You'll need to replace all of your $_POST inside the form with this:
<?php if (isset($_POST['name'])){ echo htmlspecialchars($_POST['name']); } ?> so you won't see those errors anymore. Also, you should be using $_POST, not $_post.
Alternatively, you can put error_reporting(0); at the top of your file and it will hide all of these warnings. However, it's not reccomended because if there is a real error you won't know what it is until you remove that line.

Data not entered in database

Why am I unable to enter data in to db?
<?php include ( './includes/header.php' );
$error = "";
if (#$_POST['send']) {
$name = mysql_real_escape_string(strip_tags($_POST['name']));
$email = mysql_real_escape_string(strip_tags($_POST['email']));
$message = mysql_real_escape_string(strip_tags($_POST['message']));
if ($name == "") {
$error = "Name cannot be left empty.";
}
else if ($email == "") {
$error = "Enter valid email id";
}
else if ($message == "") {
$error = "Message cannot be left empty.";
}
else{
//send message
$sendmessage = mysql_query("INSERT INTO contact VALUES('','$name','$email','$message')",$db1) or die(mysql_error());
$error = "Message sent!!";
}
}
?>
<meta property="og:title" content="Contact Us" />
<meta property="og:description" content="For any help, drop us a mail" />
<meta property="og:image" content="http://studyfoyer.org/images/contactus.jpg" />
<title>Contact Us</title>
</head>
<?php include('includes/navigation.php');?>
<div class="container">
<div class="row">
<form class="log-page" action="contact.php" method="POST">
<h2 class="form-signin-heading">Get in touch</h2>
<div class="input-prepend">
<label for="InputUsername">Name</label>
<input type="text" class="form-control" name='name' placeholder="Name" required autofocus>
</div>
<div class="input-prepend">
<label for="InputEmail">Email</label>
<input type="email" class="form-control" name='email' placeholder="Email address" required>
</div>
<div class="input-prepend">
<label for="InputMessage">Message</label>
<textarea class="form-control" rows="3" name="message" placeholder="Your message" required></textarea>
</div>
<div class="controls form-inline">
<button class="btn btn-primary" name='send' type="submit">Send</button>
</div>
<?php echo $error; ?>
</div>
</form>
</div>
</div>
Db connection is done through header.php
I've two websites(both on localhost) using same db, for contact info. can this affect?
As the code seems to run fine on other one.
It should be if (isset($_POST['send'])) instead of if (#$_POST['send']). isset function will return true is $_POST['send'] is "set". Same files for db connection will not affect anything.
Your code is vulnerable to SQL injection. You must use prepared statements to safely sanitize user's input.

Categories