PHP Custom Email using PHPMailer - php

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

Related

I get an Error when I try to redirect my PHP form to another page after the fields has been received

I get an Error when I try to redirect my PHP form to another page after the fields has been received.
I created a form, and validated the inputs. Now i want to redirect the user to the home page, when the click on the submit button.
I first checked if there's error on the input and if there's no error, the user should be redirected to the home. I don't know what i did wrong but i got this Error after i clicked on the submit button.
The error message:
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at postmaster#localhost to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Apache/2.4.46 (Win64) OpenSSL/1.1.1g PHP/7.4.11 Server at 127.0.0.1 Port 80
This is my code:
<?php
$email = $title = $ingredients = '';
$error = [];
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// check for email
if(empty($_POST['email'])){
$error['email'] = ' Email is empty';
} else {
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error['email'] = ' Email must contain # and .';
}
}
// check for title
if(empty($_POST['title'])){
$error['title'] = ' Title is empty';
} else {
$title = $_POST['title'];
if(!preg_match('/^[a-zA-Z\s]+$/', $title)){
$error['title'] = 'Title must be letters and spaces';
}
}
// check for ingredients
if(empty($_POST['ingredients'])){
$error['ingredients'] = ' Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
if(!preg_match('/^([a-zA-Z\s]+)(,\s*[a-zA-Z\s]*)*$/', $ingredients)){
$error['ingredients'] = 'Ingreients can only contain letters and comma seperated';
}
}
if(array_filter($error)){
} else {
die(header('Location : index.php'));
}
}
function xss_safe($value){
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php'?>
<form action="form.php" method="POST">
<div class="input_div">
<label >Email :</label>
<input type="text" name="email" value="<?= xss_safe($email) ?>">
<?= isset($error['email']) ? '<div class="error_msg">'.$error['email'].'</div>' : '' ?>
<div class="input_div" >
<label >Pizza Title :</label>
<input type="text" name="title" value="<?= xss_safe($title) ?>" >
<?= isset($error['title']) ? '<div class="error_msg">'.$error['title'].'</div>' : '' ?>
<div class="input_div" >
<label >Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value="<?= xss_safe($ingredients) ?>">
<?= isset($error['ingredients']) ? '<div class="error_msg">'.$error['ingredients'].'</div>' : '' ?>
<div class="input_div" >
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?= include 'template/footer.php' ?>
</html>
Maybe you try to redirect to the not exiting page at
<form action="form.php" method="POST">
Check if your file name is form.php and you call the form from /form.php
Check the screenshot: http://joxi.net/8AnKGpqIyje8Vr

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

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

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