Self Submit PHP Form Validation - php

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

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.

Send mail with PHP by validating google reCAPTCHA

I want to send a mail with PHP with validation by google reCAPTCHA. I write the following code. It seems everything is ok. but it is showing a error every time Something is wrong. Please check the error bellow. please help me someone.
<?php
if (isset($_POST['submit'])) {
$name = trim($_POST['name']);
$email = $_POST['email'];
$subject = trim($_POST['subject']);
$message = $_POST['message'];
// Google reCAPTCHA
require_once('recaptchalib.php');
$privatekey = "6Lcnk_USAAAAAHhVB97WBfaXq4-XN1DkCHjLO3j-";
$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$captchaErr = "The reCAPTCHA wasn't entered correctly. Please try it again.";
} else {
// Your code here to handle a successful verification
$validCaptcha = ture;
}
// Validate email address with PHP
if (empty($email)) {
$emailErr = "Email is required";
}else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}else{
$validEmail = true;
}
// Validate name with PHP
if (!empty($name)) {
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space are allowed.";
}
} else {
$validName = true;
}
// Validate message with PHP
if ( strlen($message) < 15 ) {
$messageErr = "At least 15 letters required.";
} else {
$validMessage = true;
}
// If all validation are true than send mail
$to = 'example#yahoo.com';
$headers = 'From: $name <$email>'."\r\n";
if ( $validCaptcha && $validEmail && $validName && $validMessage ) {
$sendMail = mail( $to, $subject, $message, $headers );
}
// Show message to user
if ( $sendMail ) {
$sendMailSucc = '<div class="">Email has been sent successful.</div>';
} else {
$sendMailErr = '<div class="error">Something is wrong. Please check the error bellow.</div>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>reCAPTCHA</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<script type="text/javascript">
var RecaptchaOptions = {
// red, white, blackglass, clean
theme : 'clean'
};
</script>
<form action="" class="contact_form" method="POST">
<div class="confirmation">
<?php echo $sendMailSucc; ?><?php echo $sendMailErr; ?>
</div>
<div>
<label for="">Full Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>">
<span class="error"><?php echo $nameErr; ?></span>
</div>
<div>
<label for="">Email:</label>
<input type="text" name="email" value="<?php echo $email; ?>">
<span class="error"><?php echo $emailErr; ?></span>
</div>
<div>
<label for="">Subject:</label>
<input type="text" name="subject" value="<?php echo $subject; ?>">
</div>
<div>
<label for="message">Message:</label>
<textarea name="message" id="" cols="30" rows="10"><?php echo $message; ?></textarea>
<span class="error"><?php echo $messageErr; ?></span>
</div>
<div>
<?php
require_once('recaptchalib.php');
$publickey = "6Lcnk_USAAAAADYvvrn9_CE1-HvAjke4GlcQolYE"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<span class="error"><?php echo $captchaErr; ?></span>
</div>
<div>
<input type="submit" name="submit" value="Send">
</div>
</form>
</div>

Undefined variable Trying to fix my contact form

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
}

Contact File wont work

on my website I have an automatic contact formular, it runs on my localhost server, but if I load the File onto my Server it won't work. It seems like the submit doesn't work, it doesn't throw an error message it just reloads the page. I've done a lot of code review, but couldn`t find any issue until now.
The strange thing to me is, that the code works on my localhost but not on the server...
You can test it yourself here:
http://144.76.1.46/RequestStream.php
And heres the code:
<?php
$your_email ='censored#gmail.com';
session_start();
$errors = '';
$name = '';
$visitor_email = '';
$user_message = '';
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
///------------Do Validations-------------
if(empty($name)||empty($visitor_email))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
//Note: the captcha code is compared case insensitively.
//if you want case sensitive match, update the check above to
// strcmp()
$errors .= "\n The captcha code does not match!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "A user $name submitted the contact form:\n".
"Name: $name\n".
"Email: $visitor_email \n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body, $headers);
header('Location: thank-you.html');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
// censored
}
else
{
return false;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact Us</title>
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="censored" type="text/javascript"></script>
</head>
<body>
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id='contact_form_errorloc' class='err'></div>
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<p>
<label for='name'>Streamname: </label><br>
<input type="text" name="name" value='<?php echo htmlentities($name) ?>'>
</p>
<p>
<label for='email'>Your Email: (for possible further queries) </label><br>
<input type="text" name="email" value='<?php echo htmlentities($visitor_email) ?>'>
</p>
<p>
<label for='message'>Streamlink and explanation why he should be listed on Lol Streamgalleries: (preferably with links to reliable sources (such as leagepedia for example)</label> <br>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
</p>
<p>
<img src="html-contact-form-captcha/captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("contact_form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</body>
</html>
Edit:
the error console helped me a little bit, there was a reference error with the javascript file, fixed it now, but sadly still won't work.
you named your button submit but checking for $_POST['Submit']
try isset($_POST['submit'])
or
$_POST['submit'] == 'Submit'

Categories