alternative to closing if statement in php also trouble with arrays - php

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; ?>

Related

How do you properly send session variables to email?

I am working on a project where I send the information being stored in the session variable $_SESSION['favourites'].
I made use of the print_r function print_r($_SESSION, true) and it did work with the output being as follows
Array
(
[favourites] => Array
(
[0] => Array
(
[item_id] => 3
)
[1] => Array
(
[item_id] => 11
)
)
)
Instead I implemented a foreach with a while loop to display the contents and store them in a variable $email_message. The problem with the code is that since $email_message is a variable it is being overwritten and echoed in a while loop.
My main objective is to send all the information in the session variable over email.
This is the phpmailer code including the foreach and while loop mentioned above.
<?php
use PHPMailer\PHPMailer\PHPMailer;
foreach($_SESSION["favourites"] as $key => $value)
{
$id = $value['item_id'];
$sql= "SELECT * FROM menu WHERE id = '$id'";
$result=mysqli_query($conn, $sql);
$resultcheck=mysqli_num_rows($result);
while($row=mysqli_fetch_assoc($result))
{
$email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';
}
echo $email_message;
}
if(isset($_POST['fullname']) && isset($_POST['email']))
{
$name = $_POST['fullname'];
$email = $_POST['email'];
$subject = 'My favourite\'s list as of '. date("Y/m/d");
//Calling the PHPMailer 'functions'
require_once "vendor\phpmailer\phpmailer\src\PHPMailer.php";
require_once "vendor\phpmailer\phpmailer\src\SMTP.php";
require_once "vendor\phpmailer\phpmailer\src\Exception.php";
$mail = new PHPMailer();
//SMTP Settings
//$mail -> SMTPDebug = 3;
$mail -> isSMTP();
$mail -> Host = "smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail -> Username = "cis1045sem2a2021#gmail.com";
$mail -> Password = 'universityofmalta';
$mail -> Port = 587;
$mail -> SMTPSecure = "tls";
//Email Settings
$mail -> isHTML(true);
$mail -> setFrom($email, $name);
$mail -> addAddress("cis1045sem2a2021#gmail.com");
$mail -> Subject = $subject;
$mail -> Body = $email_message;
if ($mail->send()) {
echo "Email is sent!";
} else {
echo "Something is wrong: <br><br>" . $mail->ErrorInfo;
}
}
?>
This is the favourites page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>El Tabata</title>
<link rel="shortcut icon" type="image/x-icon" href="./assets/images/mexican-mascot.png"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="./assets/CSS/styles.css">
<link rel="stylesheet" href="./assets/CSS/responsive.css">
</head>
<body>
<?php
include 'header.php';
include_once 'dbHandler.php';
if(isset($_SESSION))
{
session_destroy();
}
session_start();
?>
<!-- THE REMOVAL FROM FAVOURITES -->
<?php
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["favourites"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["favourites"][$keys]);
echo 'Item has been removed successfully';
echo '<script>window.location="favourites.php"</script>';
}
}
}
}
if(!empty($_SESSION['favourites']))
{
?>
<section class="container">
<ul id="contact_form" class="food-cards">
<!-- DISPLAYING THE ITEMS IN THE SESSION VARIABLE THROUGH DATABASE -->
<?php
foreach($_SESSION["favourites"] as $key => $value)
{
$id = $value['item_id'];
$sql= "SELECT * FROM menu WHERE id = '$id'";
$result=mysqli_query($conn, $sql);
$resultcheck=mysqli_num_rows($result);
while($row=mysqli_fetch_assoc($result))
{
?>
<li class="card-info">
<div class="food-card">
<div class="food-pic">
<img src="./assets/images/english-breakfast.png" alt="">
</div>
<div class="food-cont">
<h2 class="food-title">
<?php echo $row["name"]; ?>
</h2>
<div class="price-fav-btn">
<div class="price">
<?php echo "€".$row["price"]; ?>
</div>
<input type="hidden" name="hidden_id" value="<?php echo $row["id"]; ?>" />
<a style="color: white;" href="favourites.php?action=delete&id=<?php echo $id; ?>">Remove from favorits</a>
</div>
</div>
</div>
</li>
<?php
}
}
?>
</ul>
<div class="form-fav">
<form id="contact_form" method="POST">
<input type="text" name="fullname" placeholder="Full Name" required>
<input type="text" name="email" placeholder="Email" required>
<!-- <input type="text" name="body" placeholder="Start typing your message" required> -->
<button class="frm-btn" type="submit" name="submit" value="Submit">Submit</button>
</form>
</div>
</section>
<?php
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
require 'emailfunction.php';
}
else
{
?>
<section>
<div class="container">
<h4> Please add an item to your favourite's list. </h4>
<img src="./assets/images/sad-taco.jpg" alt="sad-taco">
</div>
</section>
<?php
} //end of main if-else statement
?>
<?php include 'footer.php' ?>
<script src="main.js"></script>
</body>
</html>
This is the html preview
Html Preview
This is the email preview where it is only sending 1 item only.
Function is sending 1 item only
This is what I am trying to achieve where it sends every item in 1 email.
What I am trying to achieve
If i understood correctly the problem is here:
$email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';
This way you always replacing the value in $email_message
Instead of that you should concatenate the message as follows
First declare $email_message = ''; before the loop
And in the loop write:
$email_message .= ($row['id']). ($row['name']). ($row['price']).'<br>';
or
$email_message .= ($row['id']). ($row['name']). ($row['price']).PHP_EOL;
And by the way the help is coming from Malta too ;)
Change this:
$email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';
to this:
$email_message .= ($row['id']). ($row['name']). ($row['price']).'<br>';
That's what El_Vanja was saying.

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().

My call to a function is apparently incorrect, I know it's not, but it's not clear why

I'm trying a tutorial about making a private inbox feature, everything went well apart from the fact I get a 500 server error every time I try to press send. I have checked out the logs for what could be causing this error and here's what I received: PHP Fatal error: Call to undefined function fetch_users_id() in /apps/bla/web/inboxPage.php on line 17, referer: http://hinat.local/inboxPage.php
I have checked the function to see if anything is out of place, but cannot spot anything that could be throwing it off.
Would appreciate another pair of eyes to help me see what I have done wrong here.
Thanks in advance!
inboxPage.php:
<?php
if(isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if(empty($_POST['to'])){
$errors[] = 'You must enter at least one name.';
} else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
} else {
$user_names = explode(',',$_POST['to']);
//Will remove and trailing spaces before and after name
foreach ($user_names as &$name){
$name = trim($name);
}
$user_id = fetch_users_id($user_names);
if(count($user_id) !== count($user_names)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($user_names, array_keys($user_id)));
}
}
if(empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
}
if(empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
if(empty($errors)){
}
}
if(isset($errors)){
//Form has been submitted but errors have occured
if(empty($errors)){
echo '<div class="msg success"> Your message has been sent! Return to your Inbox</div>';
//Form has been submittied and errors have occured
} else {
foreach ($errors as $errors) {
echo '<div class="msg error">', $errors, '</div>';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="site.css" >
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,400" rel="stylesheet">
</head>
<body>
<!-- Header -->
<header class="primary-header container group">
<h1 class="logo">
<!-- <img src="../home/wendy/Pictures/Logo.png" alt="Website Logo"><br> -->
</h1>
<h3 class="tagline"> Cardiff, Wales </h3>
<nav class="nav primary-nav">
<ul>
<li>Home</li><!--
--><li>Login</li><!--
--><li>Register</li><!--
--><li>Tutors</li><!--
--><li>About Us</li><!--
--><li>Contact Us</li>
</ul>
</nav>
</header>
<form action="" method= "post">
<section class="row">
<div class="grid">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" value="<?php if (isset($_POST['to'])) echo htmlentities($_POST['to']); ?>" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" value="<?php if (isset($_POST['subject'])) echo htmlentities($_POST['subject']); ?>" />
</div>
<div>
<textarea name="body" rows="20" cols="110"><?php if (isset($_POST['body'])) echo htmlentities($_POST['body']); ?></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</div>
</section>
</form>
<footer class="primary-footer container group">
<small> ©</small>
<nav class="nav">
<ul>
<li>Home</li><!--
--><li>Login<!--
--><li>Tutors<!--
--><li>Register<!--
--><li>About Us<!--
--><li>Contact Us
</ul>
</nav>
</footer>
</body>
</html>
users.php:
<?php
function fetch_users_id($user_names){
foreach($user_names as &$name) {
$name = mysql_real_escape_string($name);
}
$results = mysql_query("SELECT id, Username FROM users WHERE Username IN ('" . implode("', '", $user_names) . "')");
$names = array();
while (($row = mysql_fetch_assoc($results)) !== false){
$names[$row['Username']] = $row['id'];
}
return $names;
}
?>
The function fetch_users_id does not exist in inboxPage.php
You must include or require users.php in inboxPage.php if you want to use that function within that file.
<?php
include("users.php");

php email form validation and regular expressions

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. :)

Form $_SESSION data Issue

I have designed a form which check validation when it is sent, I am using Swiftmailer and all of the validation works however I have a problem. When I return back to the contact form the errors are still there if they filled it out wrong so...
name is required!
email is required!
the errors only go when it passes validation.
How do I refresh the page when the user leaves and comes back to a fresh form?
Contact form:
<?php
session_start();
?>
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Send a message</title>
</head>
<body>
<div class="container">
<div <?php if(isset($_SESSION['form_message'])) { echo 'style="color: green"'; } elseif (isset($_SESSION['form_errors'])) { echo 'style="color: red"'; } ?>>
<?php
if(isset($_SESSION['form_message']))
{
echo $_SESSION['form_message'];
unset($_SESSION['form_data']);
}
elseif(isset($_SESSION['form_errors']))
{
echo '<b>You have the following errors:</b>';
echo "<br>";
foreach($_SESSION['form_errors'] as $display_err) {
echo $display_err . "<br>";
}
}
?>
</div>
<form name="contact" method="post" action="swift_mail.php">
<div>
<label for="name">Full name</label><br />
<input type="text" name="name" id="name" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['name'] ; } ?>" />
</div>
<div>
<label for="email">Email Address</label><br />
<input type="text" name="email" id="email" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['email'] ; } ?>" />
</div>
<div>
<label for="comment">Comment</label><br />
<textarea name="comment" id="comment"><?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['comment'] ; } ?></textarea>
<input type="submit" value="submit" name="submit_msg"/>
</div>
</form>
</div>
</body>
</html>
</code>
swift
<?php
session_start();
require_once 'Swift-5.0.3/lib/swift_required.php';
require 'vendor/autoload.php';
if(isset($_POST['submit_msg'])) {
/*
Validate data before it is posted
*/
$rule_set = array (
'name' => array(
'required'
),
'email' => array(
'required'
),
'comment' => array(
'required'
)
);
/*
Checking Validation
*/
$validation_result = SimpleValidator\Validator::validate($_POST, $rule_set);
if ($validation_result->isSuccess() == true ) {
/*
Contact Form Information
*/
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Main Point of contact
$email_address = 'ben#bubbledesign.co.uk';
// Composed Message
$body_msg = "Name: " . $name . "<br>" . "Comments: " .$comment;
/*
Swift Mail Transport
*/
$transport = Swift_MailTransport::newInstance();
$mail = Swift_Mailer::newInstance($transport);
/*
Create the Swift Message
*/
$message = Swift_Message::newInstance('Subject line')
->setFrom($email)
->setTo($email_address)
->setBody($body_msg, "text/html");
/*
Send Swift Message
*/
$result = $mail->send($message);
$_SESSION['form_message'] = "Thank you for your message someone will be in touch soon.";
unset($_SESSION['form_errors']);
unset($_SESSION['form_data']);
header('location: contact-form.php');
} else {
$_SESSION['form_data'] = $_POST;
$_SESSION['form_errors'] = $validation_result->getErrors();
header('Location: contact-form.php');
}
}
?>

Categories