php email form validation and regular expressions - php

I am trying to teach myself how to create a contact form and have got it working to a point where I can send emails to the set email address and validate the email address but would also like to validate the other input fields but am having trouble with this.
I have tried only validating the name but cannot get the regular expression condition to work and am not sure on if it is best pulling back all the validation errors in one variable.
Not if the foreach loop on the if empty is confusing things more than they should be or not.
Any advise will be much appreciated.
Below the index.php code.
<?php
session_start();
// include the security php
require_once 'security.php';
// setting the errors to the session to get rid of the index error message
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
$mailSent = isset($_SESSION['sucess']) ? $_SESSION['sucess'] : [];
$email_ok = isset($_SESSION['validation']) ? $_SESSION['validation'] : [];
$name_ok = isset($_SESSION['validation']) ? $_SESSION['validation'] : [];
// print_r($email_ok);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8">
<title>demo contact form</title>
<style type="text/css">
input{
display: block;
}
div.main{
display: block;
width: 960px;
margin: 0 auto;
}
.warning{
color: red;
}
</style>
</head>
<body>
<div class="main">
<!-- error message display -->
<?php if(!empty($errors)): ?>
<div class="panel warning">
<ul><li><?php echo implode('</li><li>', $errors); ?></li></ul>
</div>
<?php endif; ?>
<?php if(!empty($mailSent)): ?>
<div class="panel">
<p><?php echo ($mailSent); ?></p>
</div>
<?php endif; ?>
<form action="mail.php" method="post">
<input type="text" name="name" placeholder="Your name" <?php echo isset($fields['name']) ? 'value="' .e($fields['name']). '"' : ''?>/>
<?php
if(!empty($name_ok)): ?>
<p class="warning"><?php echo ($name_ok[0]); ?></p>
<?php endif;
?>
<input type="text" name="email" placeholder="example#email.com" <?php echo isset($fields['email']) ? 'value="' .e($fields['email']). '"' : ''?>/>
<?php
if(!empty($email_ok)): ?>
<p class="warning"><?php echo ($email_ok[0]); ?></p>
<?php endif;
?>
<textarea name="message"><?php echo isset($fields['message']) ? e($fields['message']) : ''?></textarea>
<input type="submit" name="submit" value="Send">
</form>
</div>
</body>
</html>
<?php
// destroy the session so if the user moves away from the page and comes back the prior sessions will be gone
unset($_SESSION['errors']);
unset($_SESSION['fields']);
unset($_SESSION['sucess']);
unset($_SESSION['validation']);
?>
and the mail.php code
<?php
// start session to pass data around
session_start();
// include the php mailer files
require_once 'libs/phpmailer/PHPMailerAutoload.php';
$errors = [];
$validation = [];
$ok_name = '/[a-zA-Z\s]+/';
// checking what is set in the post array
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
// echo "all set";
// place all inputs into a varible so that we can out but them on for each loops
$fields = [
'name' => trim($_POST['name']),
'email' => trim($_POST['email']),
'message' => trim($_POST['message'])
];
foreach ($fields as $field => $data) {
// checking if a field is empty
echo '<pre>'.print_r($field).'</pre>';
die();
if(empty($data)){
$errors[] = 'The '.$field. ' field is required';
}
elseif
(filter_var($fields['email'], FILTER_VALIDATE_EMAIL) == false){
$validation[] = 'Enter a corect email address';
}
elseif(preg_match($ok_name, $fields['name']) == false){
$validation[] = 'Use only letters and spaces';
}
}
// name validation
// email address valiadtion
// send email via phpmailer
// if the $errors are empty
if(empty($errors || $validation)){
$m = new PHPMailer;// set a new instance of phpmailer
// these are teh details to connect to gmail via smtp
$m->isSMTP();
$m->SMTPAuth = true;
$m->Mailer = 'smtp';
$m->Host = 'smtp.example.com';
$m->Username = 'example#example.com';
$m->Password = 'nottelling';
$m->SMTPSercure = 'tls';// ssl
$m->Port = 587;// 465
$m->isHTML();// for messages that include html
$m->Subject = 'Contact form Protfolio website';
$m->Body = 'From: '.$fields['name']. '('.$fields['email'].')<p>'.$fields['message'].'</p>';
$m->FromName = 'Contact';
$m->SMTPDebug = 2;
$m->AddReplyTo($fields['email'], $fields['name']);
$m->addAddress('example#example.com', 'Name Name');
if($m->send()){
$_SESSION['sucess'] = 'Thank you for your email, I will be in touch soon.';
header('location: index1.php');
die();
}
else{
$errors[] = 'Sorry, could not send your email.';
}
}
}
else{
$errors[] = 'something went wrong';
}
// save the error message to the sessions super golbal variable
$_SESSION['errors'] =$errors;
// save input data for a sticky form
$_SESSION['fields'] =$fields;
$_SESSION['validation'] =$validation;
// redirect back to the page
header('location: index1.php');
?>

The problem is your regex just looks for one of the accepted characters to occur. Instead, you should check if any invalid characters occur with a double negative.
$errors = [];
$validation = [];
$bad_name = '/[^a-zA-Z\s]/';
//...
elseif(!preg_match($ok_name, $fields['name']) == false){
$validation[] = 'Use only letters and spaces';
}
/[^a-zA-Z\s]/ looks for any characters not included in the braces and the ! takes the opposite result. It will only be true if those characters are the only ones present in the string.

Please try this code to validate the email form:
$email = "test#email"; // Invalid email address, put your `$fields['email']`
$regex = "^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
if (preg_match( $regex, $email ) ) {
echo $email . " is a valid email.";
} else {
echo $email . " is an invalid email.";
}
Or you can use :
filter_var($fields['email'], FILTER_VALIDATE_EMAIL) && preg_match($regex, $fields['email'])
And please use empty rather than isset hope this help you a little. :)

Related

PHP form with multiple steps and validation

I'm new to PHP and I'm trying to create an easy form that has multiple steps. For each step, a validation of the input is happening before the user is directed to the next page. If the validation fails, the user should stay on the same page and an error message should be displayed. In the end, all entries that the user has made should be displayed in an overview page.
What I have been doing to solve this, is to use a boolean for each page and only once this is true, the user can go to the next page. This is not working as expected unfortunately and I guess it has something to do with sessions in PHP... I also guess that there's a nicer way to do this. I would appreciate some help!
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
session_start();
$_SESSION['$entryOne'] = "";
$_SESSION['$entryOneErr'] = $_SESSION['$emptyFieldErr'] = "";
$_SESSION['entryOneIsValid'] = false;
$_SESSION['$entryTwo'] = "";
$_SESSION['$entryTwoErr'] = "";
$_SESSION['entryTwoIsValid'] = false;
// Validation for first page
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryOne'])) {
if (!empty($_POST["entryOne"])) {
// Check for special characters
$_SESSION['$entryOne'] = removeWhitespaces($_POST["entryOne"]);
$_SESSION['$entryOneErr'] = testForIllegalCharError($_SESSION['$entryOne'], $_SESSION['$entryOneErr']);
// If error text is empty set first page to valid
if(empty($_SESSION['$entryOneErr'])){
$_SESSION['$entryOneIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
// Validation for second page
} else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryTwo'])) {
if (!empty($_POST["entryTwo"])) {
// Check for special characters
$_SESSION['$entryTwo'] = removeWhitespaces($_POST["entryTwo"]);
$_SESSION['$entryTwoErr'] = testForIllegalCharError($_SESSION['$entryTwo'], $_SESSION['$entryTwoErr']);
// If error text is empty set second page to valid
if(empty($_SESSION['$entryTwoErr'])){
$_SESSION['$entryTwoIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
}
//Remove whitespaces at beginning and end of an entry
function removeWhitespaces($data) {
$data = trim($data);
return $data;
}
//Check that no special characters were entered. If so, set error
function testForIllegalCharError($wish, $error){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar,$wish)) {
$error = "Special characters are not allowed";
} else {
$error = "";
}
return $error;
}
?>
<?php if (isset($_POST['submitEntryOne']) && $_SESSION['$entryOneIsValid'] && !$_SESSION['$entryTwoIsValid']): ?>
<h2>Second page</h2>
<p>Entry from first Page: <?php echo $_SESSION['$entryOne'];?></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Entry Two: <input type="text" name="entryTwo" value="<?php echo $_SESSION['$entryTwo'];?>">
<span class="error"><?php echo $_SESSION['$entryTwoErr'];?></span>
<br><br>
<input type="submit" name="submitEntryTwo" value="Next">
</form>
<?php elseif (isset($_POST['submitEntryTwo']) && $_SESSION['$entryTwoIsValid']): ?>
<h2>Overview</h2>
<p>First entry: <?php echo $_SESSION['$entryOne'];?></p>
<p>Second Entry: <?php echo $_SESSION['$entryTwo'];?></p>
<?php else: ?>
<h2>First page</h2>
<span class="error"><?php echo $_SESSION['$emptyFieldErr'];?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
First entry: <input type="text" name="entryOne" value="<?php echo $_SESSION['$entryOne'];?>">
<span class="error"> <?php echo $_SESSION['$entryOneErr'];?></span>
<br><br>
<input type="submit" name="submitEntryOne" value="Next">
</form>
<?php endif; ?>
</body>
</html>
You are setting your session variables to "" at the top of your script.
Check if your variable is set before setting to blank.
Check if Session Variable is Set First
<?php
//If variable is set, use it. Otherwise, set to null.
// This will carry the variable session to session.
$entryOne = isset($_REQUEST['entryOne']) ? $_REQUEST['entryOne'] : null;
if($entryOne) {
doSomething();
}
?>
Tips
Then you can use <?= notation to also echo the variable.
Do this $_SESSION['variable'] instead of $_SESSION['$variable'] (you'll spare yourself some variable mistakes).
<h2>Second page</h2>
<p>Entry from first Page: <?= $entryOne ?></p>
Example Script
This could be dramatically improved, but for a quick pass:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Check that no special characters were entered. If so, set error
function hasIllegalChar($input){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar, $input)) {
return true;
}
return false;
}
session_start();
// Destroy session and redirect if reset form link is pressed.
if(isset($_GET['resetForm']) && $_GET['resetForm'] == "yes")
{
echo "SESSION DESTROY";
session_destroy();
header("Location: ?");
}
// Session
$page = isset($_SESSION['page']) ? $_SESSION['page'] : 1;
$errors = [];
// Value history.
$valueOne = isset($_SESSION['valueOne']) ? $_SESSION['valueOne'] : null;
$valueTwo = isset($_SESSION['valueTwo']) ? $_SESSION['valueTwo'] : null;
// Clean inputs here
$fieldOne = isset($_REQUEST['fieldOne']) ? trim($_REQUEST['fieldOne']) : null;
$fieldTwo = isset($_REQUEST['fieldTwo']) ? trim($_REQUEST['fieldTwo']) : null;
// First form
if ($page == 1) {
// If field two is submitted:
if ($fieldOne) {
//Validate inputs
if(hasIllegalChar($fieldOne)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueOne = $_SESSION['valueOne'] = $fieldOne;
$page = $_SESSION['page'] = 2;
}
}
}
// Second form
else if ($page == 2) {
// If field two is submitted:
if ($fieldTwo) {
//Validate inputs
if(hasIllegalChar($fieldTwo)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueTwo = $_SESSION['valueTwo'] = $fieldTwo;
$page = $_SESSION['page'] = 3;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
// troubleshoot
if (true) {
echo "<pre>";
var_dump($_REQUEST);
var_dump($_SESSION);
echo "</pre>";
}
echo "<h1>Page " . $page . '</h1>';
if (count($errors) > 0) {
$errorMsg = implode('<br/>',$errors);
echo '<div class="error">Some errors occurred:<br/>' . $errorMsg . '</div>';
}
?>
<?php if ($page == 3): ?>
<h2>Overview</h2>
<p>First entry: <?= $valueOne;?></p>
<p>Second Entry: <?= $valueTwo;?></p>
Reset
<?php elseif ($page == 2): ?>
<p>Entry from first Page: <?= $valueOne; ?></p>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
Entry Two: <input type="text" name="fieldTwo" value="<?= $fieldTwo ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php else: ?>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
<br><br>
Entry One: <input type="text" name="fieldOne" value="<?= $fieldOne; ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php endif; ?>
</body>
<html>
You can run the following command to test out the page without using a fancy tool like WAMP or LAMP.
php -S localhost:8000 index.php
You can now access in the browser at http://localhost:8000.

PHP Custom Email using PHPMailer

I am designing an email feature for a client,
the main requirements is to keep user on same page if user has some errors
in email, the errors should be shown on the same page.
For that I have created this HTML (PHP)
<?php
session_start();
require_once '../helpers/security.php';
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHPmailer</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<div class="contact">
<?php if(!empty($errors)): ?>
<div class="panel">
<ul>
<li><?php echo implode('</li><li>', $errors); ?></li>
</ul>
</div>
<?php endif; ?>
<form action="contact.php" method="POST">
<label>
Your Name*
<input type="text" name="name" autocomplete="off"<?php echo isset($fields['name']) ? 'value="'.e($fields['name']).'"' : '' ?>>
</label>
<label>
Your Email*
<input type="text" name="email" autocomplete="off"<?php echo isset($fields['email']) ? 'value="'.e($fields['email']).'"' : '' ?>>
</label>
<label>
Your Message*
<textarea name="message" rows="8"><?php echo isset($fields['message']) ? e($fields['message']) : '' ?></textarea>
</label>
<input type="submit" value="Send">
<p class="muted">* means a required field</p>
</form>
</div>
</body>
</html>
<?php
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>
And this is my PHP code
<?php
session_start();
require_once '../phpmailer/PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
$fields = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
];
foreach($fields as $field => $data){
if(empty($data)){
$errors[] = 'The '.$field.' field is required';
}
}
if(empty($errors)){
$m= new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
/*$m->SMTPDebug = 1; */
$m->Host = 'smtp.gmail.com';
$m->Username = 'mymail#gmail.com';
$m->Password = 'mypass';
$m->SMTPSecure = 'ssl';
$m->Port = 465;
$m->isHTML();
$m->Subject = 'Contact form submitted';
$m->Body = 'From: '.$fields['name'].' ('.$fields['email'].')<p>'.$fields['message'].'</p>';
$m->FromName = 'Contact';
/*$m->AddReplyTo($fields['email'], $fields['name']);*/
$m->AddAddress('mymail#gmail.com', 'My Name');
if($m->send()){
header('Location: http://facebook.com');
die();
}
else {
$errors[]= 'Error';
}
}
}
else{
$errors[] = 'something went wrong';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: http://google.com');
?>
I have added additional security code
<?php
function e($string){
return htmlentities ($string, ENT_QUOTES, 'UTF-8', false);
}
?>
I have tried this code but it won't work it gives me "500" server error on the index page as well as contact.php page
I have checked with ";" and other general PHP errors
I have checked just by echoing the variables in PHP (PHP works :P )
On the index page if I remove
? $_SESSION['errors'] : [];
? $_SESSION['fields'] : [];
From
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
The index page shows form HTML but when I submit the form I get 500 server error on contact.php
Please help me out this code, Thanks in Advanced
To get rid of the 500 Internal server error:
A) Place this snippet right after
ini_set('display_errors', 'on');
error_reporting(-1);
B) If A is not working, try creating a .htaccess file in the web-root directory with this in it:
php_value error_reporting -1
php_flag display_errors on
C) If B is not working, then your apache\httpd server does not have AllowOverride enabled. You then should change the php.ini (same as B)
(one should never do all the above in production. Only use this while developing)
Now you should be able to see the error, which will be probably that [] is not supported by your PHP version.
Try changing all [] to array().

php validation on submit when jump from one page to another

In this program when i am clicking submit button the page directly goes on other page 2222.php. The error message not pop up.. I just want hit error message when clicking on submit button...
php_validation.php
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"])) //---------------------------------------------- -------------------------
{
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
//-----------------------------------------------------------------------
}
if (empty($_POST["email"])) //---------------------------------------------- -------------------------
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"]))
{
$genderError = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" name="myForm" action="2222.php">
<p>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError;?></span>
</p>
<br><br>
<p>
Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError;?></span>
</p>
<br><br>
<p>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">*<?php echo $genderError;?></span><br><br />
</p>
<input class="submit" type="submit" name="submit" value="Submit" >
</form>
</body>
2222.php
<?php
$name = $_POST['fname'];
$email = $_POST['email'];
$radio = $_POST['gender'];
echo "<h2>Your Input:</h2>";
echo "user name is: ".$name;
echo "<br>";
echo "user email is: ".$email;
echo "<br>";
echo "user is ".$radio;
?>
So I've done a quick code for you :
Here is your "php_validation.php" :
<?php
//Init error var
$nameError = '';
$emailError = '';
$genderError = '';
//Did we have an error ?
if(isset($_GET['error'])){
//Split error return into an array
$errorList = explode('_', $_GET['error']);
//Verify every possible error
if(in_array('name',$errorList)){
$nameError = 'Please enter your name<br>';
}
if(in_array('email',$errorList)){
$emailError = 'Please enter your email<br>';
}
if(in_array('gender',$errorList)){
$genderError = 'Please enter your gender';
}
}
?>
I didnt changed the form
Then this is your "2222.php" :
<?php
$error ='';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//When we receive data
if(isset($_POST)){
//Verify all possible data and set error
if(!empty($_POST['fname'])){
$name = test_input($_POST['fname']);
}else{
$error .= 'name_';
}
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
}else{
$error .= 'email_';
}
if(!empty($_POST['gender'])){
$radio = test_input($_POST['gender']);
}else{
$error .= 'gender_';
}
//if we have an error then redirect to form with error
if(!empty($error)){
header("Location:php_validation.php?error=".$error);
}
}
?>
Didnt changed your output on this page either.
So as I said previously when you here is what happend when you click the submit button :
Submit Click
Form sent to 2222.php as $_POST and you're redirected to this page
There is no way that could be working if your form is posting on an other page than the one where the check is made.
Since your form's action is "2222.php", on click the submit button will automatically redirect you to 2222.php before doing anything.
If you want to check what you've received by your form, you can do it in your "2222.php", then redirect it with the error message to php_validation.php
You could do one of the following things:
Do all the checking in Javascript "onClick" function
Do Ajax call "onClick" to a handler page, get the validation message from that page.
Do the validation on "2222.php" page
action back to the same page (since you are doing some validation here) and redirect after validation on "2222.php" page
Now depends only on you which fits your program.
If you want to stay on the same page you could submit the form to an iframe, as the results of the processing script would be displayed in the iframe itself.
Example:
files:
file-with-form.php
form-submit-processing-file.php
Code examples:
file-with-form.php
<!DOCTYPE html>
<html>
<head>
<title>[Your page title]</title>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<!-- Form -->
<form action="[path-to-form-submit-process]" method="[GET|POST]"
target="form-processor">
<div>
<label>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError ?></span>
</label>
</div>
<div>
<label>Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError ?></span>
</label>
</div>
<div>
<label>Gender:
<p><input type="radio" name="gender" value="female"> Female</p>
<p><input type="radio" name="gender" value="male"> Male</p>
<p><span class="error">*<?php echo $genderError ?></span></p>
</label>
<input class="submit" type="submit" name="submit" value="Submit" >
</div>
</form>
<!-- The iframe to submit the form to -->
<iframe name="form-processor" id="form-processor"
src="[path-to-form-submit-process]"></iframe>
<!--
NOTE: The error message spans are left there just because you had them
in your code, those will not work here at this point, actually depending
on your php configuration will most probably throw errors/warnings,
because such variables were not defined at all...
-->
</body>
</html>
As:
[path-to-form-submit-process] - a placeholder to be replaced with the URL to the file/ Controller -> Action that would process the passed form data
[*] - placeholders that should be replaced with the values for your case
form-submit-processing-file.php
<?php
# Processing the form fields and displaying the messages
$post = $_POST;
# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable
# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];
function addErrorMessage($message, &$messages, &$errorFlag)
{
$errorFlag = true;
$errorMessageTemplate = '<p class="error-message">{message}</p>';
array_push($messages, str_replace('{message}', $message,
$errorMessageTemplate));
}
// Validating the email
$email = array_key_exists('email', $post)
? $post['email']
: null;
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
// Raising the flag for an error on validation
addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}
// ........
// validation of rest of fields
// ........
$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
// ........
} catch (Exception $e) {
$internalError = true;
}
# Stop execution on internal error
if ($internalError === true)
{
?>
<h2>Sorry, there's an error on our side... we'll do all in our
powers to fix it right away!</h2>
<?php
exit;
}
# Displaying the results
if ($invalidFormData === true) {
// Building errors message
$messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
$messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}
// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);
// Displaying the messages:
echo implode('', $messages);
However I believe this should be done via an AJAX call insted.
Also there are a lot of bad practices in this case, so I would suggest checking out some design patterns and architectures as MVC for instance and consider using a framework like Symfony/Laravel/CodeIgniter... There are a lot of tools that will make your life easier :)

Contact.php send email but doesn't redirect

I am working on the contact form for my Music Project's website.
The contact form seems to be working ok. If i input every field it sends the email (i get it ok on my gmail account) and if i don't input every field it gives error messages.
But the strange thing is that after i hit send i get a blank page (address: MySiteRoot/contact.php )and it doesn't redirect.
If i then click on the browsers "Go Back" button, i get the correct "error" messages, either the error or the message sent.
Why isn't is redirecting? Any ideas?
I have tried adding
exit();
after the
header('Location: /index.php');
but it didn't make any change.
I have both the index.php and the contact php on my site's root folder.
here is the code of my CONTACT.PHP
<?php
session_start();
require_once 'libs/phpmailer/PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['name'], $_POST['email'], $_POST['message'])) {
$fields = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
];
foreach($fields as $field => $data) {
if(empty($data)) {
$errors[] = 'The ' . '<b>' . $field . '</b>' . ' field is required.';
}
}
if(empty($errors)) {
$m = new PHPMailer;
$m -> isSMTP();
$m -> SMTPAuth = true;
/*$m -> SMTPDebug = 1;*/
$m -> Host = 'smtp.gmail.com';
$m -> Username = ''; /* TOOK THEM OUT HERE ON THE POST ONLY */
$m -> Password = ''; /* TOOK THEM OUT HERE ON THE POST ONLY */
$m -> SMTPSecure = 'ssl';
$m -> SMTPKeepAlive = true;
$m -> Port = 465;
$m -> isHTML(true);
$m -> Subject = '4Elements Message';
$m -> Body = 'From: ' . $fields['name'] . ' (' . $fields['email'] . ')<p>' . $fields['message'] . '</p>';
$m -> FromName = '4Elements Contact';
$m -> AddAddress('anatis#gmail.com', 'Anatis');
if($m -> Send()) {
$errors[] = 'Thanks! Your message was sent!';
header('Location: /index.php');
} else {
$errors[] = 'Sorry, could not send email. Please try again later.';
}
}
} else {
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: /index.php');
on my INDEX.PHP i have at the beginning:
<?php
session_start();
require_once 'security.php';
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
?>
<!DOCTYPE HTML>
... THEN COMES SOME HTML CONTENT
Later on comes the FORM:
<?php if(!empty($errors)): ?>
<div class="panel">
<ul><li><?php echo implode('</li><li>', $errors); ?></li></ul>
</div> <!-- end of .panel -->
<?php endif; ?>
<form action="contact.php" method="post">
<label>
<input type="text" name="name" autocomplete="off" placeholder="Name" <?php echo isset($fields['name']) ? ' value="' . e($fields['name']) . '"' : ''?>>
</label>
<label>
<input type="email" name="email" autocomplete="off" placeholder="Email" <?php echo isset($fields['email']) ? ' value="' . e($fields['email']) . '"' : ''?>>
</label>
<label>
<textarea name="message" rows="10" placeholder="Message"><?php echo isset($fields['message']) ? e($fields['message']) : ''?></textarea>
</label>
<input id="submitbutton" type="submit" value="send">
</form>
and then at the end of the index.php i still have:
<?php
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>
i am working on my local server, with MAMP running PHP 5.6.2
Any ideas on what is going on? Thanks!
try to remove the header('Location: /index.php'); inside the m->Send() and let the only one at the end of the script.
Even replace $errors = [] with $errors = Array() at the begin.
Have you tried with using javascript instead of header('Location: /index.php');
echo '<script>window.location.href="/index.php";</script>'
Also, have you checked any warning or error log file. If you are getting this type of error message "Cannot modify header information - headers already sent" then try this link How to fix "Headers already sent" error in PHP
I hope it should work for you.

alternative to closing if statement in php also trouble with arrays

Thank you in advance for looking at my code and helping me with the problem i am having. I am trying to build a simple contact form. The thing is when i hit my submit button everything that gets directed to the next page displays everything into an array. How can i go about fixing this?
Also, my if statement is giving me a hard time how can i go about fixing this? Am i using the wrong type of arrays?
contact.php
<?php
session_start();
require_once 'PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
$fields = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
];
foreach($fields as $field => $data) {
if(empty($data)){
$errors[] = 'The ' . $field . ' field is required.';
}
}
if(empty($errors)){
$m = new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
$m->Host = 'smtp.gmail.com';
$m->Username = 'none#gmail.com';
$m->Host = 'Pa$$w0rd1';
$m->SMTPSecure = 'ssl';
$m->Port = '465';
$m->isHTML();
$m->Subject = 'Contact form submitted';
$m->Body = 'From: ' . $fields['name'] . ' (' . $fields['email'] . ')<p>' . $fields['message'] . '</p>';
$m->From = 'Contact';
$m->AddAddress('none#gmail.com', 'name');
if($m-> send()){
header('Location: thankyou.php');
die();
} else {
$errors[] = 'Sorry, could not send email. Try again late.';
}
}
} else {
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: contactform.php');
?>
contactform.php
<?php
session_start();
require_once 'security.php';
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Contact Us</title>
<link rel="stylesheet" href="css/website.css">
</head>
<center><body>
<div class="contact">
<?php if(!empty($errors)): ?>
<div class="panel">
<ul><li><?php echo implode(('</li><li>'), $errors); ?></li></ul>
</div>
<?php endif; ?>
<form action="contact.php" method="post">
<label>
Your name *
<input type="text" name="name" autocomplete="off">
</label>
<br><label>
Your email address *
<input type="text" name="email" autocomplete="off">
</label>
<br><label>
Your message or concern *
<textarea name="message" rows="8"></textarea>
</label>
<input type="submit" value="Send">
<p class="muted">* means a required field</p>
</form>
</div>
</body></center>
</html>
<?php
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>
This is the if statement i am referring to in the above code
<?php if(!empty($errors)); ?>
<div class="panel">
<ul><li><?php echo implode(('</li><li>'), $errors); ?></li></ul>
</div>
<?php endif ?>
Please Please Please help me with this.
Problem is semicolon at end of your if statement.
If you want to use if with endif you need to use ":" like this:
if(!empty($errors)):
code;
endif;
Try this:
<?php if(!empty($errors)): ?>
<div class="panel">
<ul><li><?php echo implode(('</li><li>'), $errors); ?></li></ul>
</div>
<?php endif; ?>
The proper way to use if ... endif is:
<?php if (condition): ?>
// Things to do when condition is true
<?php endif; ?>

Categories