As I am beginner in using PHPmailer trying to send mail in localhost (XAMPP) server. I included class.phpmailer.php and class.smtp.php file but I'm getting an error message "there is an error" To resolve this I changed gmail account IMAP settings as Enable and and allow less secure apps.
But the problem has been not resolved. I get:
Warning:fwrite() expects parameter 1 to be resource, integer given in C:\xampp\htdocs\email-phpmailer\class\class.smtp.php on line 1023
Code I have Tried
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if($error == '')
{
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'smtp.gmail.com'; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = '587'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'abc#gmail.com'; //Sets SMTP username
$mail->Password = 'MyPass'; //Sets SMTP password
$mail->SMTPSecure = 'ssl'; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = $_POST["email"]; //Sets the From email address for the message
$mail->FromName = $_POST["name"]; //Sets the From name of the message
$mail->AddAddress('xyz#gmail.com', 'its me'); //Adds a "To" address
//$mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
$mail->WordWrap = 50; //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = $_POST["subject"]; //Sets the Subject of the message
$mail->Body = $_POST["message"]; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$error = '<label class="text-success">Thank you for contacting us</label>';
}
else
{
$error = '<label class="text-danger">There is an Error</label>';
}
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Send an Email on Form Submission using PHP with PHPMailer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<div class="row">
<div class="col-md-8" style="margin:0 auto; float:none;">
<h3 align="center">Send an Email on Form Submission using PHP with PHPMailer</h3>
<br />
<?php echo $error; ?>
<form method="post">
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Email</label>
<input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Enter Subject</label>
<input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label>Enter Message</label>
<textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" value="Submit" class="btn btn-info" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Related
I am trying to send email to more than 2 emails if it is possible with the bellow code, but currently with the code i have i can only send to 1 email but i want to send it more than 4 users. Also i will fetch users from a database but right now it is not a problem for me, id prefer solving the first one
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if($error == '')
{
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'smtp.gmail.com'; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = '465'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'example#domain.co'; //Sets SMTP username
$mail->Password = 'xxxxxxxxxxx'; //Sets SMTP password
$mail->SMTPSecure = 'ssl'; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = $_POST["email"]; //Sets the From email address for the message
$mail->FromName = 'name'; //Sets the From name of the message
$mail->AddAddress($_POST["email"]); //Adds a "To" address
$mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
$mail->WordWrap = 50; //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = $_POST["subject"]; //Sets the Subject of the message
$mail->Body = $_POST["message"]; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$error = '<label class="text-success">Thank you for contacting us</label>';
}
else
{
$error = '<label class="text-danger">There is an Error</label>';
}
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Send an Email on Form Submission using PHP with PHPMailer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<div class="row">
<div class="col-md-8" style="margin:0 auto; float:none;">
<h3 align="center">Send an Email on Form Submission using PHP with PHPMailer</h3>
<br />
<?php echo $error; ?>
<form method="post">
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Email</label>
<input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Enter Subject</label>
<input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label>Enter Message</label>
<textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" value="Submit" class="btn btn-info" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>```
you have multiple choice here, in first you can create a list of email input like by adding email[1] in your input component.
<input type="email" name="email[1]" value="<? $email[1] ?>" >
The number is used to identify the input in your php ,like this $_POST[email][x].
In the " back-end " section, you will add a loop around
foreach($_POST['email] as $emailAdress){
$mail->addAdress($emailAdress)
}
i hope that will help you
I am new to php but I would like to use a phpmailer in my project. I have followed the steps from here: https://github.com/PHPMailer/PHPMailer but the form somehow does not send and I get a 404 problem. Can anyone help me understand what it is that I am doing wrong here?
My html file:
<div class="container">
<form method="POST" action="form.php">
<div class="section7">
<div>
<input type="text" name="company" placeholder="Firma*" required><br>
<input type="text" name="surname" placeholder="Nazwisko*" required><br>
<input type="email" name="email" placeholder="E-mail*" required><br>
<textarea name="message" placeholder="Wiadomość*" required></textarea>
</div>
<div>
<input type="text" name="address_code" placeholder="Kod pocztowy*" required><br>
<input type="text" name="name" placeholder="Imię*" required><br>
<input type="tel" name="phone" placeholder="Nr telefonu*" required>
</div>
</div>
<div class="checkbox">
<label for="policy"></label><input type="checkbox" id="policy" name="policy" value="policy" required>
</label>Wyrażam zgodę na przetwarzanie moich danych osobowych zgodnie z ustawą z dnia 29.08.1997 (Dz.U.nr 133,poz.883) o ich ochronie.</label><br>
</div>
<div class="btn-submit">
<input type="submit" value="Wyślij">
</div>
</form>
</div>
My php form file:
<?php
require_once('mailer/class.phpmailer.php');
require_once('mailer/class.smtp.php');
require_once('mailer/PHPMailerAutoload.php');
require_once('phpmaileroauthgoogle.php');
header('Content-Type: application/json');
$mail = new PHPMailer(true);
try {
$name = $_POST['name'];
$surname = $_POST['surname'];
$company = $_POST['company'];
$email = $_POST['email'];
$tel = $_POST['phone'];
$address = $_POST['address_code'];
$messageText = $_POST['message'];
if (empty($name) || empty($email) || empty($tel) || empty($messageText) || empty($surname) || empty($company) || empty($address)) {
http_response_code(400);
echo json_encode("All fields are required.");
exit;
}
$messageText .= "\nNumer telefonu: " . $tel;
$mail->isSMTP();
$mail->CharSet = "UTF-8";
$mail->FromName = "$name";
$mail->Host = "smtp.gmail.com";
$mail->Mailer = "smtp";
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->SMTPAutoTLS = false;
$mail->Username = "myemail";
$mail->Password = "mypassword";
$mail->SetFrom("myemail");
$mail->Subject = "Message sent from xxx website";
$mail->Body = $messageText;
$mail->AddAddress("myemail");
$mail->AddReplyTo($email);
if ($mail->send()) {
echo json_encode("Thank you the message has been sent.");
} else {
http_response_code(400);
echo json_encode("Sorry, there was an error");
}
} catch (\Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
I am having some trouble, I am trying to submit a form with php and phpmailer.
So what I did is trying to make a form following w3school complete form example and then I wondered if I could send it through email. I found phpmailer and I tried using it but it is not sending.
I am using the $contactsend to know if I can send form or not (after the validation have been done). So in case $contactsend is 0 then I cannot send and if it is 1 then I can send the form.
However I am almost sure that there is an issue with it but I don't know why.
How can I understand what is going wrong?
Here is the code I have :
<?php
$contactnameErr = $emailErr = $phoneErr = $subjectErr = $messageErr = "";
$contactname = $email = $phone = $subject = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$contactsend= 1;
if (empty($_POST["contactname"])) {
$contactnameErr = "* Name is required";
$contactsend= 0;
} else {
$contactname = test_input($_POST["contactname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactname)) {
$contactnameErr = "* Only letters and white space allowed";
$contactsend= 0;
}
}
if (empty($_POST["contactemail"])) {
$contactemailErr = "* Email is required";
$contactsend= 0;
} else {
$contactemail = test_input($_POST["contactemail"]);
// check if e-mail address is well-formed
if (!filter_var($contactemail, FILTER_VALIDATE_EMAIL)) {
$contactemailErr = "* Invalid email format";
$contactsend= 0;
}
}
if (empty($_POST["contactphone"])) {
$contactphoneErr = "* Phone is required";
$contactsend= 0;
} else {
$contactphone = test_input($_POST["contactphone"]);
$contactsend= 0;
}
if (empty($_POST["contactsubject"])) {
$contactsubjectErr = "* Subject is required";
$contactsend= 0;
} else {
$contactsubject = test_input($_POST["contactsubject"]);
$contactsend= 0;
}
if (empty($_POST["contactmessage"])) {
$contactmessageErr = "* Message is required";
$contactsend= 0;
} else {
$contactmessage = test_input($_POST["contactmessage"]);
$contactsend= 0;
}
echo $contactsend;
if($contactsend== 1)
{
//send mail
$message = "\nSpecial Events , Contact Us . \nName : " . $contactname . "\nEmail : " . $contactemail . "\nPhone : " . $contactphone
. "\nSubject : " . $contactsubject ."\nMessage : " . $contactmessage;
require("/home/specialeventsleb/public_html/phpmailer/PHPMailer/class.phpmailer.php");
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = 'email1';
$mail->Password = 'password1';
$mail->SetFrom('email1', 'FromEmail');
$mail->AddAddress('email1', 'ToEmail');
$mail->AddAddress('email2', 'ToEmail1');
$mail->AddAddress('email3', 'ToEmail2');
$mail->SMTPDebug = true;
$mail->Timeout = 2000;
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
$mail->Debugoutput = 'echo';
$mail->Subject = 'Message from Special Events Website';
$mail->Body = $message;
$mail->send();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="ContactUs">
<!--<img class="ComputerBanner" src="Pictures/map/ContactUsBanner.png" />-->
<img class="MobileBanner" src="Pictures/map/ContactUsBannerMobile.png" />
<div class="ContactBox">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h2>SEND US A MESSAGE!</h2>
<span>We'd be happy to hear from you.</span>
<input name="contactname" placeholder="Name" type="text" value="<?php echo $contactname;?>"/> <span class="error"> <?php echo $contactnameErr;?></span>
<input name="contactemail" placeholder="Email" type="text" value="<?php echo $contactemail;?>" /><span class="error"> <?php echo $contactemailErr;?></span>
<input name="contactphone" placeholder="Phone #" type="text" value="<?php echo $contactphone;?>" /><span class="error"> <?php echo $contactphoneErr;?></span>
<input name="contactsubject" placeholder="Subject" type="text" value="<?php echo $contactsubject;?>" /><span class="error"> <?php echo $contactsubjectErr;?></span>
<textarea name="contactmessage" placeholder="Message"><?php echo $contactmessage;?></textarea><span class="error"> <?php echo $contactmessageErr;?></span>
<input type="submit" name="submit" value="Send" class="contact-button" />
</form>
</div>
</div>
First the operations you're checking with if($contactsend== 1) are not called because your script forces $contactsend = 0 checking "contactsubject", "contactphone", "contactmessage"..
Then you have to set these
$mail->SetFrom('email1', 'FromEmail');
$mail->AddAddress('email1', 'ToEmail');
$mail->AddAddress('email2', 'ToEmail1');
$mail->AddAddress('email3', 'ToEmail2');
with valid email addresses..
Example with
$mail->AddAddress($contactemail, 'ToEmail');
which get the value from the POST
For any other infos read this
https://github.com/PHPMailer/PHPMailer
i am trying to send a random number to an email but unable to this is the code that i have been able to come up with so far
please help if possible
sendmail.php
$to = $_POST['email'];
$header ='From:admin#domain.com';
$subject ='Verification Code';
if(empty($to))
{
echo "Email is Empty";
}
else
{
if (mail($to,$subject,$message,$header)){
echo 'Check Your Email FOr verfication code';
}
else{
echo 'Failed';
}
}
index.php
<form action = "register.php" method="POST">
<p>Username</p>
<input type="text" name="username" maxlength="40" value='<?php if(isset($username)) echo $username ?>'"><br>
<p>New Password</p>
<input type="password" name="password">
<p>email</p>
<input type="text" name="email" maxlength="40" value='<?php if(isset($email)) echo $email ?>'"> <br><br>
<input type="submit" value="Register"> <br><br>
</form>
In form(index.php)
<form action="sendmail.php" method="post">
<lable>email</lable>>
<input type="text" name="email" maxlength="40">
<br>
<input type="submit" value="Register">
</form>
In sendmail.php
$rand= rand(10, 20)// random number generator
$to = $_POST['email'];
$header ='From:admin#domain.com';
$subject ='Verification Code';
$message = "Your Random number is";
$message .= $rand;
$message .= "Thank you-Admin";
if(empty($to))
{
echo "Email is Empty";
}
else
{
if (mail($to,$subject,$message,$header)){
echo 'Check Your Email FOr verfication code';
}
else{
echo 'Failed';
}
}
You forgot to add semicolon at the end of first line
$rand= mt_rand(100000, 999999)
It should be
$rand= mt_rand(100000, 999999);
I think the hosting service that You're using does not accept sending using mail() functions. Maybe for security reasons to prevent virus-like php scripts to send spams from Your account.
So create admin#domain.com email account and using PHPMailer send Your email:
require __DIR__.'/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.hostname.com';
$mail->SMTPAuth = true;
$mail->Username = 'no-reply#domain.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('admin#domain.com');
$mail->addAddress($to);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
download link and examples here: https://github.com/PHPMailer/PHPMailer
I am working on a contact form in PHP. My knowledge of PHP is pretty much non-existent.
I've tried for a while to get a HTML form to submit to PHP form to have its text fields validated and required if blank but couldn't get anything to work. I also don't know AJAX, otherwise, would have attempted that.
So, have resorted to having a PHP self-form inside the HTML page.
This is the current version:
<?php
// define variables and set to empty values
$firstNameErr = $lastNameErr = $emailErr = $messageErr = "";
$first_name = $last_name = $email = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["first-name"])) {
$firstNameErr = "First name is required";
} else {
$first_name = test_input($_POST["first-name"]);
}
if (empty($_POST["last-name"])) {
$lastNameErr = "Last name is required";
} else {
$last_name = test_input($_POST["last-name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is the form on the same page:
<form class="ui form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label>First Name</label>
<input name="first-name" id="first-name" placeholder="First Name" type="text">
<span class="error">* <?php echo $firstNameErr;?></span>
</div>
<div class="field">
<label>Last Name</label>
<input name="last-name" id="last-name" placeholder="Last Name" type="text">
<span class="error">* <?php echo $lastNameErr;?></span>
</div>
<div class="field">
<label>Email</label>
<input name="email" id="email" placeholder="Email" type="email">
<span class="error">* <?php echo $emailErr;?></span>
</div>
<div class="field">
<label>Message</label>
<textarea rows="2" placeholder="Please type in your message" name="message" id="message"></textarea>
<span class="error">* <?php echo $messageErr;?></span>
</div>
<button class="ui button" type="submit">Submit</button>
</form>
Is there a way to do this in two different pages, ie, form in first page, and carried over to the second page in sessions mode? Or is this acceptable for a commercial site? Please let me know. Thank you.
Addendum
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = filter_vars(test_input($_POST["email"], FILTER_VALIDATE_EMAIL));
}
Addendum 2
I have included this at the bottom of the php stuff, ie, after the function test_input.header('location: php_mailer_form.php'); Is that the correct placement of it?
But for some reason when I attempt to visit the contact.php form it doesn't even show up, it just goes straight to the error form which I have at the bottom of the php_mailer_form.php.
if(!$mail->send()) {
header('location: url/contactError.html');
} else {
header('location: url/contactResult.html');
}
Why? (please let me know if I need to include additional information).
Addendum 3
<?php
session_start();
$first_name = $_SESSION['first-name'];
$last_name = $_SESSION['last-name'];
$email = $_SESSION['email'];
$message = nl2br($_SESSION['message']);
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'host_specified'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'email_specified'; // SMTP username
$mail->Password = 'password_specified'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;
$mail->addReplyTo( $email, $first_name );
$mail->addAddress( $email, $first_name );
$mail->addAddress( 'email_specified', 'Staff' );
$mail->From = 'email_specified';
$mail->FromName = 'Staff';
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Hotel Room Request';
$mail->Body = $message;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
if(!$mail->send()) {
header('location: url/contactError.html');
} else {
header('location: url/contactResult.html');
}
Addendum 4
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Contact</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css">
.ui.fixed.sticky + p {
margin-top: 39px;
}
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!isset($_POST["first-name"])) {
$firstNameErr = "First name is required";
} else {
$first_name = test_input($_POST["first-name"]);
}
if (!isset($_POST["last-name"])) {
$lastNameErr = "Last name is required";
} else {
$last_name = test_input($_POST["last-name"]);
}
if (!isset($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (!isset($_POST["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if(isset($first_name) && isset($last_name) && isset($email) && isset($message))
{
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['email'] = $email;
$_SESSION['message'] = $message;
header("Location: contact9Sessions.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="ui container">
<div class="ui segment">
<div>
<div class="ui fluid five item tabular menu">
<a class="item" href="index.html">Home</a>
<a class="item" href="about.html">About</a>
<a class="item" href="rooms.html">Rooms Info & Rates</a>
<a class="item" href="book.html">To Book</a>
<a class="item" href="contact.html">Contact</a>
</div>
</div>
<div class="ui two column stackable grid">
<div class="ten wide column">
<form class="ui form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label>First Name</label>
<input name="first-name" id="first-name" placeholder="First Name" type="text">
<?php if(isset($firstNameErr)) print ('<span class="error">* ' . $firstNameErr . '</span>'); ?>
</div>
<div class="field">
<label>Last Name</label>
<input name="last-name" id="last-name" placeholder="Last Name" type="text">
<?php if(isset($lastNameErr)) print ('<span class="error">* ' . $lastNameErr . '</span>'); ?>
</div>
<div class="field">
<label>Email</label>
<input name="email" id="email" placeholder="Email" type="email">
<?php if(isset($emailErr)) print ('<span class="error">* ' . $emailErr . '</span>'); ?>
</div>
<div class="field">
<label>Message</label>
<textarea rows="2" placeholder="Please type in your message" name="message" id="message"></textarea>
<?php if(isset($messageErr)) print ('<span class="error">* ' . $messageErr . '</span>'); ?>
</div>
<button class="ui button" type="submit">Submit</button>
</form>
</div>
<div class="six wide column">
<br><br>
<img class="ui centered large bordered rounded image" src="images/tobereplaced.jpg">
</div>
</div>
</div>
<div class="ui two column grid">
<div class="ui left aligned ">
<p>Left Footer Stuff Here</p>
</div>
<div class="ui right aligned">
<p>Right Footer Stuff Here</p>
</div>
</div>
</div>
</body>
</html>
Here is a basic form send example. This can all be on one page. PHP at the top, before all the html loads to browser, <form> html down anywhere in the <body> of the html page:
EDIT:
I have updated the code to include your PHP Emailer.
<?php
class EmailEngine
{
public static function Send($settings = false)
{
$email = (!empty($settings['email']))? $settings['email']:false;
$first_name = (!empty($settings['first-name']))? $settings['first-name']:false;
$last_name = (!empty($settings['last-name']))? $settings['last-name']:false;
$message = (!empty($settings['message']))? $settings['message']:false;
$alt_message = (!empty($settings['alt_message']))? $settings['alt_message']:'To view the message, please use an HTML compatible email viewer!';
require(__DIR__.'/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'host_specified'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'email_specified'; // SMTP username
$mail->Password = 'password_specified'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;
$mail->addReplyTo( $email, $first_name );
$mail->addAddress( $email, $first_name );
$mail->addAddress( 'email_specified', 'Staff' );
$mail->From = 'email_specified';
$mail->FromName = 'Staff';
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Hotel Room Request';
$mail->Body = $message;
$mail->AltBody = $alt_message;
return $mail->send();
}
}
// Just make an error reporting function to return errors
function error_report($val = false)
{
$array["first-name"] = "First name is required";
$array["last-name"] = "Last name is required";
$array["email"] = "Email is required";
$array["message"] = "A message is required";
return (isset($array[$val]))? $array[$val] :false;
}
// Sanitize. I add false so no error is thrown if not set
function sanitize_vals($data = false)
{
if(empty($data))
return false;
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// If a value is posted (any will do from your form) process the rest of the $_POST
if(isset($_POST["first-name"])) {
// Just loop through the $_POST instead of doing all the manual if/else...
foreach($_POST as $key => $value) {
// This specifically processes your email address
if(($key == 'email')) {
// If not valid email, send to errors
if(!filter_var($value,FILTER_VALIDATE_EMAIL))
$errors[$key] = error_report('email');
else
$payload[$key] = $value;
}
// This processes the rest
else {
$value = sanitize_vals($value);
// Checks for empty
if(empty($value))
$errors[$key] = error_report($key);
else
$payload[$key] = $value;
}
}
// If all is good and no errors set, send the email
if(!isset($errors)) {
// SEND MAIL HERE.
$page = (EmailEngine::Send($payload))? "Result" : "Error";
header("Location: url/contact{$page}.html");
exit;
}
}
?>
<form class="ui form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label>First Name</label>
<input name="first-name" id="first-name" placeholder="First Name" type="text" value="<?php if(!empty($_POST['first-name'])) echo htmlspecialchars($_POST['first-name'],ENT_QUOTES);?>" />
<span class="error">* <?php if(!empty($errors['first-name'])) echo $errors['first-name'];?></span> </div>
<div class="field">
<label>Last Name</label>
<input name="last-name" id="last-name" placeholder="Last Name" type="text" value="<?php if(!empty($_POST['last-name'])) echo htmlspecialchars($_POST['last-name'],ENT_QUOTES);?>" />
<span class="error">* <?php if(!empty($errors['last-name'])) echo $errors['last-name'];?></span> </div>
<div class="field">
<label>Email</label>
<input name="email" id="email" placeholder="Email" type="email" value="<?php if(!empty($_POST['email'])) echo preg_replace('/[^0-9a-zA-Z\#\.\_\-]/',"",$_POST['email']);?>" />
<span class="error">* <?php if(!empty($errors['email'])) echo $errors['email'];?></span> </div>
<div class="field">
<label>Message</label>
<textarea rows="2" placeholder="Please type in your message" name="message" id="message"><?php if(!empty($_POST['message'])) echo htmlspecialchars($_POST['message'],ENT_QUOTES);?></textarea>
<span class="error">* <?php if(!empty($errors['message'])) echo $errors['message'];?></span> </div>
<button class="ui button" type="submit">Submit</button>
</form>
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!isset($_POST["first-name"])) {
$firstNameErr = "First name is required";
} else {
$first_name = test_input($_POST["first-name"]);
}
if (!isset($_POST["last-name"])) {
$lastNameErr = "Last name is required";
} else {
$last_name = test_input($_POST["last-name"]);
}
if (!isset($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (!isset($_POST["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if(isset($first_name) && isset($last_name) && isset($email) && isset($message))
{
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['email'] = $email;
$_SESSION['message'] = $message;
header("Location: php_mailer_form.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form class="ui form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label>First Name</label>
<input name="first-name" id="first-name" placeholder="First Name" type="text">
<?php if(isset($firstNameErr)) print ('<span class="error">* ' . $firstNameErr . '</span>'); ?>
</div>
<div class="field">
<label>Last Name</label>
<input name="last-name" id="last-name" placeholder="Last Name" type="text">
<?php if(isset($lastNameErr)) print ('<span class="error">* ' . $lastNameErr . '</span>'); ?>
</div>
<div class="field">
<label>Email</label>
<input name="email" id="email" placeholder="Email" type="email">
<?php if(isset($emailErr)) print ('<span class="error">* ' . $emailErr . '</span>'); ?>
</div>
<div class="field">
<label>Message</label>
<textarea rows="2" placeholder="Please type in your message" name="message" id="message"></textarea>
<?php if(isset($messageErr)) print ('<span class="error">* ' . $messageErr . '</span>'); ?>
</div>
<button class="ui button" type="submit">Submit</button>
</form>
Now in your other page, to access the variables, simply call "session_start();" at the top of the page as we did here, then use call "$_SESSION['message']" to get the value of message. Does this answer your question? Also note, I edited the html so that the error message div only prints if the error variable was set.