Undefined variable Trying to fix my contact form - php

I have been trying to fix my contact form wherein the data can be sent via email. But i seem to have some errors at the start. It says in the web page "Undefined variable" yet. I'm only following a tutorial that i have been reading and i'm not yet adept in PHP. I'm using XAMPP at the moment in order to run my PHP
Here is the HTML Markup
<html>
<head>
<title>Contact Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Contact Form</h1>
<p class="error"> There are some misisng fields.</p>
<?php if($error == true) { ?>
<?php } if($sent == true) { ?>
<p class="sent">Thank you for sending your message</p><?php } ?>
<div class="contactform">
<form name="contact" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="name">Name:</label>
<input type="text" name="name" />
<label for="email">Email:</label>
<input type="email" name="email" />
<label for="comments">Comments:</label>
<textarea name="comments"></textarea>
<input type="submit" name="submit" class="submit" value="submit" />
</form>
</div>
Here is the PHP Code
<?php if($_POST['submit']) {
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments'])) {
$error = true;
} else {
$to = "clestcruz#gmail.com";
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$comments = trim($_POST['comments']);
$subject = "Contact Form";
$messages = "Name: $name \r\n Email: $email \r\n Comments: $comments";
$headers = "From:" . $name;
$mailsent = mail($to, $subject, $messages, $headers);
if($mailsent){
$sent= true;
}
}
}
?>
</body>
</html>
Undefine Variables
<?php if($error == true) { ?>
<?php } if($sent == true) { ?>
if($_POST['submit']) {

Try declaring the variables before you use it. PHP will give out a notice if you don't pass a value first.
<?php
$error=false;
$sent=false;
if(isset($_POST['submit'])) {
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments'])) {
$error = true;
} else {
$to = "clestcruz#gmail.com";
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$comments = trim($_POST['comments']);
$subject = "Contact Form";
$messages = "Name: $name \r\n Email: $email \r\n Comments: $comments";
$headers = "From:" . $name;
$mailsent = mail($to, $subject, $messages, $headers);
if($mailsent){
$sent= true;
}
}
}
?>

These lines:
<?php if($error == true) { ?>
<?php } if($sent == true) { ?>
appear near the top of your HTML, but as far as I can see, there's been no PHP executed at this point, so $error and $sent won't be defined.
This line:
if($_POST['submit']) {
is testing for a value, but unless your form has been submitted, it too won't be defined. You could test this more effectively with
if (isset($_POST['submit'])) {
// do stuff
}

Related

Why is it that my $_SESSION or my 'if' statement won't trigger when split over two pages?

I am trying to make an email form that when an error occurs it displays a flash error message. I have the process split over two pages, the first is the contact.php page where the form is and the other is the validation.php page where the validation and email 'mail()' function is. I link the pages via a 'require_once("validation.php");' at the top of the contact.php page.
When I have them split over these two pages the flash message won't appear but when I have all of the code on one page only, the contact.php page, it does work. However, even though this problem is happening the email does send when the form is filled in, so I know the linking of the pages is working and some of the code is executing.
Any idea why this is occurring?
Here is a simplified version of my code:
contact.php:
<?php
require_once("validation.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>...</title>
</head>
<body>
<main class="container">
<div class="form-container">
<?php
echo '<pre>'.print_r($_POST).'</pre>';
echo '<pre>'.print_r($_SESSION['error']).'</pre>';
if ( isset($_SESSION['error']) ) {
echo('<p style="color: red;">'.$_SESSION['error']."
</p>\n");
unset($_SESSION['error']);
}
?>
<form action="contact.php" method="POST">
<label for="name">Enter your name: </label><br>
<input type="text" name="name"><br>
<label for="email">Enter your email: </label><br>
<input type="email" name="email"><br>
<label for="subject">Subject line: </label><br>
<input type="text" name="subject">
<br>
<label for="message">Message: </label><br>
<textarea name="message" cols="75" rows="10">
</textarea><br>
<input type="submit" value="Submit">
</form>
</div><!-- .form-container -->
</main>
</body>
</html>
validation.php:
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$subject = test_input($_POST["subject"]);
$message = test_input($_POST["message"]);
if ( strlen($name) < 1 || strlen($email) < 1 || strlen($subject) < 1 ||
strlen($message) < 1) {
$_SESSION['error'] = "All fields are required";
header("Location: contact.php");
return;
} else {
$to = "example#example.com";
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $name <$email>";
mail($to, $subject, $message, $headers);
}
}
function test_input($data) {
$data = trim($data);
$data = strip_tags($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The issue is caused by the use of return; as opposed to exit;;
Since the include file is not terminated, the rest of the script is processed.
Your code should be edited as such:
if (!session_id()) {
session_start();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$subject = test_input($_POST["subject"]);
$message = test_input($_POST["message"]);
if (strlen($name) < 1 || strlen($email) < 1 || strlen($subject) < 1 ||
strlen($message) < 1) {
$_SESSION['error'] = "All fields are required";
header("Location: contact.php");
exit;
}
//no need for else since when the if condition is true, it is terminated
$to = "example#example.com";
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $name <$email>";
mail($to, $subject, $message, $headers);
}
//...
Edited to answer comment question:
Include files are allowed to return a value such as an array just like a function. So when you used return it did not stop the rest of the script from executing at that point. It did however "leave" the include file.
So your script added the header and then returned void, then continued to display the HTML content after the include.
For example:
<?php
//index.php
$value = include 'my_file.php';
var_dump($value);
<?php
//my_file.php
return ['foo' => 'bar'];
Since there was textual content after the header, the redirect was also not honored.

HTML5 Contact form is submitting without any data in fields

My first time posting here so apologies if i get anything wrong. I have recently built a site from a HTML5 UP template - www.vancareleeds.co.uk. I have used the contact form that came with the template and used a simple mail.php file in the root folder to action the email to be sent to my inbox.
I have also put in Google ReCaptcha but am since struggling to force the form to validate (EG. the form can be sent without the reCaptcha being ticked and it can also be sent with no information in the fields on the form.
I have provided my code here of the .php and also the webpage itself.
If i have broken protocol or best practice for psots i apologise.
mail.php
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$mobile = $_POST['mobile'];
$vehicle = $_POST['category-vehicle'];
$service = $_POST['category-service'];
$formcontent="From: $name \n Message: $message \n Mobile: $mobile \n Vehicle: $vehicle \n Service Required: $service";
$recipient = "info#vancareleeds.co.uk";
$subject = "Contact Form from VanCare Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>
form html
<form method="post" action="mail.php">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div class="field">
<label for="email">Email</label>
<input type="email" name="email" id="email" />
</div>
<div class="field">
<label for="message">Message</label>
<textarea name="message" id="message" rows="4"></textarea>
</div>
<div class="g-recaptcha" data-theme="dark" class="g-recaptcha" data-sitekey="6Lf1OVMUAAAAAJv1fNtt-CJEFPK-Q0Ugc1CVCRVh"></div><br/>
<ul class="actions">
<li><input type="submit" value="Send Message" /></li>
</ul>
</form>
Welcome +Catalan Soccer! I would suggest to you if you are new to PHP to use var_dump(), print_r() or var_export() the result of the $_POST global array to see what was sent to your PHP script. All other things you can comment out and uncomment if you feel confident.
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'], $_POST['email'], $_POST['message']) === true) {
$name = filter_var(trim($_POST['name']), FILTER_SANITIZE_STRING);
if (empty($name) === true) {
$errors['name'][] = 'Name is empty';
} elseif (ctype_alpha($name) === false) {
$errors['name'][] = 'Name contains invalid characters';
}
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
if (empty($email) === true) {
$errors['email'][] = 'E-mail is empty';
} elseif ($email === false) {
$errors['email'][] = 'Invalid e-mail address';
}
$message = strip_tags(trim($_POST['message']));
if (empty($message) === true) {
$errors['message'][] = 'Message is empty';
}
if (count($errors) === 0) {
echo 'Thank you!';
// you can use here the sanitized user input to send the e-mail
}
}
if (count($errors) > 0) {
foreach ($errors as $field => $messages) {
echo implode(', ', $messages), '<br>';
}
}
This will test user input and print out error message.

Self Submit PHP Form Validation

I've made a PHP form to submit to self with error validation, but the form is not submitting. The idea is, when the user clicks on the submit button and hasn't filled in all required fields or email address they entered is flawed, then errors occur by adding an error class that's sorted by CSS. The CSS is fine, but the form is not submitting. I'd appreciate the help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Email</title>
</head>
<body>
<?php
$error = '';
$to = "name#example.com";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["message"])) {
$error = 'class="error" ';
} else {
$name = stripslashes(trim($_POST["name"]));
$email = stripslashes(trim($_POST["email"]));
$message = stripslashes(trim($_POST["message"]));
$pattern = '/[\r\n]|Content-Type:|Bcc:|Cc:/i';
if (preg_match($pattern, $name) || preg_match($pattern, $email)) {
$error = 'class="error" ';
}
$emailIsValid = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($name && $email && $emailIsValid && $message) {
$subject = "From $name";
$body = "Name: $name <br /> Email: $email <br /> Message: $message";
$headers = "Reply-To: $email";
$success = mail($to, $subject, $body, $headers);
if ($success) {
header("Location: /email/sent/");
} else {
header("Location: /error/");
}
}
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input <?php echo $error; ?>type="text" name="name" placeholder="Full Name" spellcheck="false">
<input <?php echo $error; ?>type="text" email="email" placeholder="Email Address" spellcheck="false">
<textarea <?php echo $error; ?>type="text" message="message" placeholder="Message" rows="6" spellcheck="false"></textarea>
<button type="submit" name="submitted">submit</button>
</form>
</body>
</html>
NOTE : You have typo mistakes in your form tag.you used double quote inside double quote.
Insted of using this
<form method="post" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
and
if ($_SERVER["REQUEST_METHOD"] == "POST") {
Use
<form method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
and
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitbutton'])) {
//SO IT WILL PERFORM ONLY WHEN SUBMIT BUTTON WAS PRESSED
For More You can Learn it here
Or Also Live Demo is available

How can i solve Failing connect to mail server?

I am trying to create a working contact form, but this warning is showing when i submit form, Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set().How can i solve this issue ? can anybody help
The main code is here
<?php
if(empty($_POST) === false)
{
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(empty($name) === true || empty($email) === true || empty($message) === true )
{
$errors[] = "Name, email and Message are required";
}
else if (filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
$errors[] = "This is not valid email address";
}
if (empty($errors)=== true)
{
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" ;
mail($to, $subject, $message, $headers);
header('Location : index.php?sent');
exit();
} }
?>
<!DOCTYPE html>
<html>
<head>
<title>A contact Form</title>
</head>
<body>
<div class="container" style="width: 350px; margin: 0 auto;">
<?php
if(empty($errors) === false)
{
echo "<ul>";
foreach ($errors as $error) {
echo "<li>" .$error. "</li>";
}
echo "</ul>";
}
?>
<form action="" method="POST">
<p>
<label for ="name">Name:</label> </br>
<input type="text" name="name" id="name"
<?php if (isset($_POST['name']) === true)
{ echo 'value =" ', strip_tags($_POST['name']), '"'; } ?>>
</p>
<p>
<label for ="email">Email:</label> </br>
<input type="text" name="email" id="email"
<?php if (isset($_POST['email']) === true)
{ echo 'value =" ', strip_tags($_POST['email']), '"'; } ?>>
</p>
<p>
<label for ="message">Message:</label> </br>
<textarea name="message" id ="message">
<?php if (isset($_POST['message']) === true)
{ echo strip_tags($_POST['message']); } ?> </textarea>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
</div>
</body>
</html>

Script should send an email containing form submission values, but no email is getting sent

So I have a HTML form with some PHP but I'm not getting any email whatsoever after submitting it. I can't find the problem! can you help me out?
Tried changing the if(isset($_POST['submit'])) { to 'enviar' but still not working.
tried putting some echos to see where it's not working. the only statement that is stopping at the else statement is stripslashes.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Before getting any email, you have to be sure the email is being sent.
$sent = mail($emailTo, $subject, $body, $headers);
var_dump($sent);
What does this code output when placed in the appropriate place?
Have you tried a simple php page to do a test Email (eg fixed content) and I assume the webserver has email configured and is prepared to relay for your address?
If this is WordPress contact form, for starters:
mail($emailTo, $subject, $body, $headers);
should be:
wp_mail($emailTo, $subject, $body, $headers);
See: wp_mail codex
Now you have to check your e-mail setup, as well as WordPress e-mail setup too.

Categories