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.
Related
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.)
Bellow is part of the code from register.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
/* running some checks of an input*/
if(sizeof($errorArray)==0) {
// redirecting to avoid form resubmission
$_SESSION['registered'] = true;
header('location: success.php',true,303);
}
else{
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['errorArray'] = $errorArray;
header('location: register.php',true,303);
}
}
Logic is simple -- if an errorArray is empty redirect to a success page, else redirect to register.php itself. To avoid form resubmission i tried to put post variables into session variable, so the user doesn't have to fill form again in case of error.
<?php
if (isset($_SESSION['errorArray'])) {
if (sizeof($_SESSION['errorArray']) != 0) {
echo '<div class="alert alert-danger" role="alert">
<h4>There were errors in Your input:</h4>';
foreach ($_SESSION['errorArray'] as $item) {
echo $item . '<br>';
}
}
$_SESSION['post'] = null;
$_SESSION['errorArray'] = null;
}
?>
This part of a code is executed later in register.php but it doesen't gives me the result I want. Somehow the variables are sett to null before the loop above is executed (??!). I have found a solution with get method that includes microtime in url passed to header , but it seams to me that there is more elegant solution that does not every time adds new values to a session variable.
Is there some way around this?
edit :
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// array to hold all the errors of input
$errorArray = [];
$emailRegex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
$nameRegex = '/^[a-z0-9][a-z0-9_]*[a-z0-9]$/';
$passwordRegex = '/^[a-z0-9][-a-z0-9_!##$?]*[a-z0-9]$/';
$email = $_POST['email'];
if (empty($email)) {
array_push($errorArray, "E-mail field required");
} else {
if (!preg_match($emailRegex, $email)) array_push($errorArray, 'Invalid email');
}
$name = $_POST['name'];
if (empty($name)) {
array_push($errorArray, "Name field required");
} else {
if (!preg_match($nameRegex, $name)) array_push($errorArray, 'Invalid name');
}
$password = $_POST['password'];
$passwordR = $_POST['passwordR'];
if (empty($passwordR) || empty($password)) {
array_push($errorArray, 'Password fields required');
} else if (!preg_match($passwordRegex, $password)) {
array_push($errorArray, 'Invalid password');
} else {
if ($password !== $passwordR) {
array_push($errorArray, 'Password inputs are not the same');
}
}
if (sizeof($errorArray) == 0) {
// redirecting to avoid form resubmission
$_SESSION['registered'] = true;
header('location: success.php', true, 303);
} else {
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['errorArray'] = $errorArray;
header('location: register.php', true, 303);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/maincss.css" type="text/css">
<meta name="viewport" content="width = device-width, initial-scale = 1, user - scalable = no">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed">
<div class="container">
Home
<ul class="navbar-brand col-xs-5"><?= (isset($username)) ? 'Welcome ' . $username : ''; ?></ul>
Login
Register
</div>
</nav>
<div class="container">
<form class="form-signin" action="register.php" method="post">
<h2 class="form-signin-heading text-center text-capitalize">Registration form</h2>
<!-- I have purposely excluded required attribute from inputs and set type="text"
for an email so all the checks could be done on server side -->
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="email" class="sr-only">Email address</label>
<input type="text" id="email" name="email" class="form-control" placeholder="Email address"
value="<?= (isset($_SESSION['post']['email'])) ? $_SESSION['post']['email'] : ''; ?>" autofocus>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="name" class="sr-only">Name</label>
<input type="text" id="name" name="name" class="form-control" placeholder="Name"
value="<?= (isset($_SESSION['post']['name'])) ? $_SESSION['post']['name'] : ''; ?>" autofocus>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password">
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="passwordR" class="sr-only">Repeat Password</label>
<input type="password" id="passwordR" name="passwordR" class="form-control"
placeholder="Repeat Password">
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row">
<div class="col-xs-4"></div>
<div class="col-xs-4 center-block">
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div>
<?php
if (isset($_SESSION['errorArray'])) {
if (sizeof($_SESSION['errorArray']) != 0) {
echo '<div class="alert alert-danger" role="alert">
<h4>There were errors in Your input:</h4>';
foreach ($_SESSION['errorArray'] as $item) {
echo $item . '<br>';
}
}
// $_SESSION['post'] = null;
// $_SESSION['errorArray'] = null;
}
?>
</div>
</form>
</body>
</html>
I have started to make a message box, where a user can send a message to me. When I run the code the boxes is working fine, but I never receive a mail, and I do not get any errors. Can anybody see if I am doing something totally wrong?
<?php
//set validation error flag as false
$error = false;
//check if form is submitted
if (isset($_POST['submit']))
{
$name = trim($_POST['txt_name']);
$fromemail = trim($_POST['txt_email']);
$subject = trim($_POST['txt_subject']);
$message = trim($_POST['txt_msg']);
//name can contain only alpha characters and space
if (!preg_match("/^[a-zA-Z ]+$/",$name))
{
$error = true;
$name_error = "Please Enter Valid Name";
}
if(!filter_var($fromemail,FILTER_VALIDATE_EMAIL))
{
$error = true;
$fromemail_error = "Please Enter Valid Email ID";
}
if(empty($subject))
{
$error = true;
$subject_error = "Please Enter Your Subject";
}
if(empty($message))
{
$error = true;
$message_error = "Please Enter Your Message";
}
if (!$error)
{
//send mail
$toemail = "test#stackoverflow.com";
$subject = "Enquiry from Visitor " . $name;
$body = "Here goes your Message Details: \n\n Name: $name \n From: $fromemail \n Message: \n $message";
$headers = "From: $fromemail\n";
$headers .= "Reply-To: $fromemail";
if (mail ($toemail, $subject, $body, $headers))
$alertmsg = '<div class="alert alert-success text-center">Message sent successfully. We will get back to you shortly!</div>';
else
$alertmsg = '<div class="alert alert-danger text-center">There is error in sending mail. Please try again later.</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 3 Contact Form Example</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 well">
<form role="form" class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactform">
<fieldset>
<legend>Bootstrap Contact Form</legend>
<div class="form-group">
<div class="col-md-12">
<label for="txt_name" class="control-label">Name</label>
</div>
<div class="col-md-12">
<input class="form-control" name="txt_name" placeholder="Your Full Name" type="text" value="<?php if($error) echo $name; ?>" />
<span class="text-danger"><?php if (isset($name_error)) echo $name_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="txt_email" class="control-label">Email ID</label>
</div>
<div class="col-md-12">
<input class="form-control" name="txt_email" placeholder="Your Email ID" type="text" value="<?php if($error) echo $fromemail; ?>" />
<span class="text-danger"><?php if (isset($fromemail_error)) echo $fromemail_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="txt_subject" class="control-label">Subject</label>
</div>
<div class="col-md-12">
<input class="form-control" name="txt_subject" placeholder="Your Subject" type="text" value="<?php if($error) echo $subject; ?>" />
<span class="text-danger"><?php if (isset($subject_error)) echo $subject_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="txt_msg" class="control-label">Message</label>
</div>
<div class="col-md-12">
<textarea class="form-control" name="txt_msg" rows="4" placeholder="Your Message"><?php if($error) echo $message; ?></textarea>
<span class="text-danger"><?php if (isset($message_error)) echo $message_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input name="submit" type="submit" class="btn btn-primary" value="Send" />
</div>
</div>
</fieldset>
</form>
<?php if (isset($alertmsg)) { echo $alertmsg; } ?>
</div>
</div>
</div>
</body>
</html>
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.
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
}