Contact Form Setup PHPMailer - php

I'm trying to get my contact form to work but since I don't have and IDE with a debugger I can't figure out where the PHP code fails.
Also, instead of a success message that replaces the message box and submit button which I think it's doing now, I would like to redirect to thank-you.html
Would appreciate some pointers.
HTML
<div class="col-md-6 text-left small-screen-center os-animation" data-os-animation="fadeInRight" data-os-animation-delay="0.3s">
<form id="contactForm" class="contact-form">
<div class="form-group form-icon-group">
<input class="form-control" id="name" name="name" placeholder="Your name *" type="text" required/>
<i class="fa fa-user"></i> </div>
<div class="form-group form-icon-group">
<input class="form-control" id="email" name="email" placeholder="Your email *" type="email" required>
<i class="fa fa-envelope"></i> </div>
<div class="form-group form-icon-group">
<input class="form-control" id="number" name="number" placeholder="Your number " type="number">
<i class="fa fa-phone"></i> </div>
<div class="form-group form-icon-group">
<input class="form-control" id="company" name="company" placeholder="Your company " type="text">
<i class="fa fa-briefcase"></i> </div>
<div class="form-group form-icon-group">
<input class="form-control" id="subject" name="subject" placeholder="Subject " type="text">
<i class="fa fa-briefcase"></i> </div>
<div class="form-group form-icon-group">
<textarea class="form-control" id="message" name="message" placeholder="Your message *" rows="5" required></textarea>
<i class="fa fa-pencil"></i> </div>
<div>
<input type="submit" value="send message" class="btn btn-link">
</div>
</form>
<div id="messages" style="padding-top:10px;"></div>
</div>
PHP
<?php
require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
// Setting up PHPMailer
$mail->IsSMTP(); // Set mailer to use SMTP
// Visit http://phpmailer.worxware.com/index.php?pg=tip_srvrs for more info on server settings
// For GMail => smtp.gmail.com
// Hotmail => smtp.live.com
// Yahoo => smtp.mail.yahoo.com
// Lycos => smtp.mail.lycos.com
// AOL => smtp.aol.com
$mail->Host = 'secure.emailsrvr.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->SMTPDebug = 3;
//This is the email that you need to set so PHPMailer will send the email from
$mail->Username = 'my#emailadress.com'; // SMTP username
$mail->Password = 'XXXXXX'; // SMTP password
$mail->SMTPSecure = 'tls';
$mail->Port = 465; // TCP port to connect to
// Add the address to send the mail to
$mail->AddAddress('my#emailadress.com');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML
// add your company name here
$company_name = 'My Company';
// choose which fields you would like to be validated separated by |
// options required - check input has content valid_email - check for valid email
$field_rules = array(
'name' => 'required',
'email' => 'required|valid_email',
'message' => 'required'
);
// change your error messages here
$error_messages = array(
'required' => 'This field is required',
'valid_email' => 'Please enter a valid email address'
);
// select where each inputs error messages will be shown
$error_placements = array(
'name' => 'top',
'email' => 'top',
'subject' => 'right',
'message' => 'right',
'submitButton' => 'right'
);
// success message
$success_message = new stdClass();
$success_message->message = 'Thanks! your message has been sent';
$success_message->field = 'submitButton';
$success_message->placement = $error_placements['submitButton'];
// mail failure message
$mail_error_message = new stdClass();
$mail_error_message->message = 'Sorry your mail was not sent - please try again later';
$mail_error_message->field = 'submitButton';
$mail_error_message->placement = $error_placements['submitButton'];
// DONT EDIT BELOW THIS LINE UNLESS YOU KNOW YOUR STUFF!
$fields = $_POST;
$returnVal = new stdClass();
$returnVal->status = 'error';
$returnVal->messages = array();
if (!empty($fields)) {
//Validate each of the fields
foreach ($field_rules as $field => $rules) {
$rules = explode('|', $rules);
foreach ($rules as $rule) {
$result = null;
if (isset($fields[$field])) {
if (!empty($rule)) {
$result = $rule($fields[$field]);
}
if ($result === false) {
$error = new stdClass();
$error->field = $field;
$error->message = $error_messages[$rule];
$error->placement = $error_placements[$field];
$returnVal->messages[] = $error;
// break from the rule loop so we only get 1 error at a time
break;
}
} else {
$returnVal->messages[] = $field . ' ' . $error_messages['required'];
}
}
}
if (empty($returnVal->messages)) { // Enable encryption, 'ssl' also accepted
$email = stripslashes(safe($fields['email']));
$body = stripslashes(safe($fields['message']));
// The sender of the form/mail
$mail->From = $email;
$mail->FromName = stripslashes(safe($fields['name']));
$mail->Subject = '[' . $company_name . ']';
$content = $email . " sent you a message from your contact form:<br><br>";
$content .= "-------<br>" . $body . "<br><br><br><br>Email: " . $email;
$mail->Body = $content;
if(#$mail->Send()) {
$returnVal->messages[] = $success_message;
$returnVal->status = 'ok';
} else {
$returnVal->messages[] = $mail_error_message;
}
}
echo json_encode($returnVal);
}
function required($str, $val = false)
{
if (!is_array($str)) {
$str = trim($str);
return ($str == '') ? false : true;
} else {
return !empty($str);
}
}
function valid_email($str)
{
return (!preg_match("/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD", $str)) ? false : true;
}
function safe($name)
{
return(str_ireplace(array("\r", "\n", '%0a', '%0d', 'Content-Type:', 'bcc:','to:','cc:'), '', $name));
}
Oh, one more thing: This contact form came with a website template and within the contact.js I found this warning:
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are mutually exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form.
What does that mean exactly? The contact.js contains code for both. Do I need to delete some of it to get it to work?
Here is the jsfiddle for the contact.js

Related

Why PHP PDO bindParam return null if include jQuery file

On every page I have jQuery modal which contains a contact form and which on every page need sent data to different email address. When a form is submitted I need to display successful response using json_encode. Also on every page I use page identifier as $pages_id=1, $pages_id=2, etc., for identify which form is submitted. However, very important, without jQuery file, complete my PHP code it's executed correctly, all data are successfully inserted into database and in Xdebug I also see that code on every line it's executed successfully. But, if I include jQuery file then in Xdebug the value for $pages_id return null. I exactly think at this line of code:
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute();
However, below is my complete PHP code:
<?php
// set error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);
$fname = $tel = $userMail = $userMessage = $email_address_id = "";
$fname_error = $tel_error = $userMail_error = $userMessage_error = "";
$error=false;
//Load the config file
$dbHost = "secret";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "secret";
$dbCharset = "utf8";
$pdo="";
try{
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
echo "Connection error: " . $e->getMessage();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['submitOwner'])){
$fname = $_POST['fname'];
$tel = $_POST['tel'];
$userMail = $_POST['userMail'];
$userMessage = $_POST['userMessage'];
if(empty($_POST['fname'])){
$error=true;
$fname_error = "Name and surname cannot be empty!";
}else{
$fname = $_POST['fname'];
if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)){
$fname_error = "Name and surname can only contain letters and spaces!";
}
}
if(empty($_POST['tel'])) {
$tel_error = "Phone number cannot be blank!";
}else{
$tel = $_POST['tel'];
if(!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$tel_error = "The phone number should contain a minimum of 9 to 15 numbers!";
}
}
if(empty($_POST['userMail'])){
$userMail_error = "Email cannot be blank!";
}else{
$userMail = $_POST['userMail'];
if(!filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
$userMail_error = "Email address is incorrect!";
}
}
if(empty($_POST['userMessage'])) {
$userMessage_error = "The content of the message cannot be empty!";
}else{
$userMessage = $_POST['userMessage'];
if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ0-9 ,.!?\'\"]*$/", $userMessage)){
$userMessage_error = "The content of the message cannot be special characters!";
}
}
if($fname_error == '' && $tel_error == '' && $userMail_error == '' && $userMessage_error == ''){
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret';
$mail->SMTPAuth = true;
$mail->Username = 'secret';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->setFrom('secret#secret.com');
$mail->Subject = "New message from visit-neum.com";
$mail->isHTML(true);
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute(); //in Xdebug this line of code return NULL for $pages_id if include jQuery file
$emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
$jsonData=array();
if(is_array($emails_other) && count($emails_other)>0){
foreach($emails_other as $email_other){
//var_dump($email_other['email_address']);
$mail->addAddress($email_other['email_address']);
$body_other = "<p>Dear {$email_other['owner_name']}, <br>" . "You just received a message from the site <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Message: </strong>" . $userMessage . "</p>";
$mail->Body = $body_other;
if($mail->send()){
$mail = "INSERT INTO visitneum.contact_owner(fname, tel, userMail, userMessage, email_address_id) VALUES(:fname, :tel, :userMail, :userMessage, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);
// Load AJAX
if($error==false){
$information['response'] = "success";
$information['content'] = "Thanks " . ucwords($fname) . "! Your message has been successfully sent to the owner of property! You will get an answer soon!";
$jsonData[] = $information;
}
}//end if mail send
else{
$information['response'] = "error";
$information['content'] = "An error has occurred! Please try again..." . $mail->ErrorInfo;
$jsonData[]=$information;
}
echo(json_encode($jsonData));
} // end foreach($emails_other as $email_other)
} // end if(is_array($emails_other) && count($emails_other)>0)
} // end if validation
} // end submitOwner
} // end REQUEST METHOD = POST
And below you can see submitHandler for my jQuery file which causes me problem:
submitHandler: function(form){
var formData=jQuery("#contactOwner").serialize();
console.log(formData);
jQuery.ajax({
url: "/inc/FormProcess.php",
type: "post",
dataType: "json",
data: formData,
success:function(jsonData) {
jQuery("#responseOwner").text(jsonData.content);
console.log(jsonData);
error: function (jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
}); // Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} // end submitHandler
And the page which contains contact form is below:
<?php
include_once './inc/FormProcess.php';
?>
<form spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Your name and surname ..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
<div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Your phone number..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
<div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Your e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope owner_icon" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Your message..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="SENT"/>
</form>
<script defer src="/JS/validateOwner.js"></script>
So, I can not figure out what is the problem and why $pages_id return null when include jQuery file. Also, I was forget to mention that code inside line if(is_array($emails_other) && count($emails_other)>0){ return number 0, so complete seguent code isn't executed, but of course this is normal, because $pages_id is null. However, I hope that somebody understand what is the problem and so, thanks in advance for any kind of help that you can give me.
page_id is null in your script because you dont set it in the script.
So why not just adding an hidden input field in your froms with the page id and then in your PHP code
$page_id = $_POST['pageId'];
i think you did not understood ajax correclty. if you post your data to /inc/FormProcess.php it is not like an include before, where you could create variables first and then include it. AJax is like a sub call to the script. it is like if you would open ONLY this scrirpt provided in URL. so at this point you dont have your variables.
you need to get the variables or send your ajax request NOT to /inc/FormProcess.php but to the script where you define the variable
All you have to do is add input type hidden at the end of the form, so my correct form should look like this:
<form spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form ajax' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Vaše ime i prezime..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
<div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Vaš broj telefona..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
<div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Vaš e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Vaša poruka..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="hidden" name="pages_id" value="<?=$pages_id?>">
<input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="POŠALJI"/>
</form>

How to link custom "Sent" Page via PHPMailer

I've recently started working with PHPMailer to email my contactforms and after some puzzling, it works great. The only 'downside' is that the user gets redirected after sending an email. For example:
If one would fill in the form here, they will be redirected to another page like this one when the message sent succesfully.
My HTML for my form is the following:
<form class="form ajax-contact-form" method="post" action="php/contact.php">
<div class="alert alert-success hidden" id="contact-success">
<strong>Votre message a été envoyé avec
succès!</strong> Merci, nous contacterons vous dès que possible.
</div>
<div class="alert alert-danger hidden" id="contact-error">
<strong>Votre message n'a pas été envoyé.</strong> Vous
avez tout rempli correctement?
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="text" name="name_" id="name_" required="" class=
"form-control" placeholder="Votre nom" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="text" name="adress_" id="subject_" required=""
class="form-control" placeholder="Votre adresse" /></label>
</div>
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="number" name="zipcode_" id="zipcode_" required=
"" class="form-control" placeholder="Code postal" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="text" name="city_" id="city_" required="" class=
"form-control" placeholder="Ville ou commune" /></label>
</div>
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="tel" name="phone_" id="phone_" required=""
class="form-control" placeholder=
"Votre numéro de téléphone" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="email" name="email_" id="email_" required=""
class="form-control" placeholder="Votre adresse d'email" /></label>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label><select name="select_" id="select_" required="" class="form-control">
<option value="Invalid">
Choisi un option
</option>
<option value="CV Ketel huren">
Je veux louer une chaudière
</option>
<option value="CV Ketel kopen">
Je veux acheter une chaudière
</option>
<option value="Ik wens meer informatie">
Je veux plus d'infos
</option>
</select></label>
</div>
</div><label>
<textarea name="message_" id="message_" cols="30" rows="10" class="form-control"
placeholder="Votre message (optionel)">
</textarea></label>
<div class="mb40"></div>
<div class="clearfix">
<div class="pull-left">
<button type="submit" class="btn btn-icon btn-e">Envoi</button>
</div>
</div>
</form>
The php for my form is the following:
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
// Include PHPMailer class
include("./PHPMailer/PHPMailerAutoload.php");
// grab reCaptcha library
require_once "./reCaptcha/recaptchalib.php";
///////////////////////////////////////////////////////////////////////
// Enter your email address below.
$to_address = "info#cvketelshuren.com";
// Enter your secret key (google captcha)
$secret = "Leftout for apparent reasons";
//////////////////////////////////////////////////////////////////////
// Verify if data has been entered
if(!empty($_POST['name_']) || !empty($_POST['adress_']) || !empty($_POST['zipcode_']) || !empty($_POST['city_']) || !empty($_POST['phone_']) || !empty($_POST['email_']) || !empty($_POST['select_'])) {
$name = $_POST['name_'];
$adress = $_POST['adress_'];
$zipcode = $_POST['zipcode_'];
$city = $_POST['city_'];
$phone = $_POST['phone_'];
$email = $_POST['email_'];
$select = $_POST['select_'];
// Configure the fields list that you want to receive on the email.
$fields = array(
0 => array(
'text' => 'Naam',
'val' => $_POST['name_']
),
1 => array(
'text' => 'Adres',
'val' => $_POST['adress_']
),
2 => array(
'text' => 'Stad',
'val' => $_POST['zipcode_']." ".$_POST['city_']
),
3 => array(
'text' => 'Select',
'val' => $_POST['select_']
),
4 => array(
'text' => 'Telefoonnummer',
'val' => $_POST['phone_']
),
5 => array(
'text' => 'Mailadres',
'val' => $_POST['email_']
),
6 => array(
'text' => 'Bericht',
'val' => $_POST['message_']
)
);
$message = "Waarde collega,<br>Er werd een contactformulier ingevuld op de site cvketelshuren.com<br>Gelieve hieronder de gegevens van de klant terug te vinden.<br>";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 0; // Debug Mode
// If you don't receive the email, try to configure the parameters below:
$mail = new PHPMailer;
$mail->Host = 'mailout.one.com';
$mail->SMTPAuth = true;
$mail->Username = '***************';
$mail->Password = '************';
$mail->SMTPSecure = false;
$mail->Port = 25;
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress($to_address);
$mail->AddReplyTo($email, $name);
if (!empty($_POST['send_copy_'])) {
$mail->AddAddress($email);
}
$mail->IsHTML(true); // Set email format to HTML
$mail->CharSet = 'UTF-8';
$mail->Subject = 'Vraag via CV Ketels Huren [NL]';
$mail->Body = $message;
// Google CAPTCHA
$resp = null; // empty response
$reCaptcha = new ReCaptcha($secret); // check secret key
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
// if captcha is ok, send email
if ($resp != null && $resp->success) {
if($mail->Send()) {
$result = array ('response'=>'success');
} else {
$result = array ('response'=>'error' , 'error_message'=> $mail->ErrorInfo);
}
} else {
$result = array ('response'=>'error' , 'error_message'=>'Google ReCaptcha did not work');
}
echo json_encode($result);
} else {
$result = array ('response'=>'error' , 'error_message'=>'Data has not been entered');
echo json_encode($result);
}
?>
As you can see, an error and success message was already coded in but if redirecting is something that should happen, I want to code a custom HTML-page. Anybody that can help me set the redirect so I can start coding?
Thanks for your time!
You are not doing any redirects here. Your form tag contains action="php/contact.php", so that's where the form will submit to. If you want to go somewhere else after processing the form submission and sending a message, you can do a redirect like this:
header('Location: some_other_url/page.php');
If the form contains errors, you could redirect back to the form, passing error messages in the URL parameters.

PHPMailer form not sending attachments

I'm trying to implement a contact form using PHPMailer but I can't make the attachment from the upload field to be sent. The contact form do work and all the other fields are sent.
I followed this tutorial with no luck.
Also tried numerous different PHP scripts such as this, this and this one, among others.
The current code I have that seems to be the most successfully used is this one:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';
// Attack #1 preventor - Spam Honeypot
if ($_POST["address"] != "") {
echo "SPAM HONEYPOT";
exit;
}
// Attack #2 preventor - Email header injection hack preventor
foreach($_POST as $value) {
if(stripos($value, 'Content-Type:') !== FALSE) {
echo "There was a problem with the information you entered.";
exit;
}
}
if (isset($_POST['inputNome']) && isset($_POST['inputEmail']) && isset($_POST['inputMensagem'])) {
//check if any of the inputs are empty
if (empty($_POST['inputNome']) || empty($_POST['inputEmail']) || empty($_POST['inputMensagem'])) {
$data = array('success' => false, 'message' => 'Preencha todos os campos requeridos.');
echo ($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host = "************"; //Gmail SMTP server address
$mail->Port = 465; //Gmail SMTP port
$mail->Encoding = '7bit';
// Authentication
$mail->Username = "*************"; // Your full Gmail address
$mail->Password = "*********"; // Your Gmail password
$mail->CharSet = 'UTF-8';
// Compose
$mail->SetFrom($_POST['inputEmail'], $_POST['inputNome']);
$mail->AddReplyTo($_POST['inputEmail'], $_POST['inputNome']);
$mail->Subject = "My Company - " . $_POST['inputAssunto']; // Subject (which isn't required)
$mail->AddAddress('name#myemail.com'); //recipient
//Add attachment
$mail->addAttachment($_FILES['inputBriefing']);
if (isset($_FILES['inputBriefing']) &&
$_FILES['inputBriefing']['error'] == UPLOAD_ERR_OK) {
$mail->addAddress($_FILES['inputBriefing']['tmp_name'],
$_FILES['inputBriefing']['name']);
}
$mail->Body = "Nome: " . $_POST['inputNome'] . "\r\nEmail: " . $_POST['inputEmail'] . "\r\nTelefone: " .$_POST['inputTelefone'] . "\r\nAssunto: " . $_POST['inputAssunto'] . "\r\nMensagem: " . stripslashes($_POST['inputMensagem']);
if(!$mail->send())
{
echo 'An error has occurred.';
exit;
}
echo 'Message successfully sent';
}
?>
And the form:
<form id="contact" method="post" action="<?php echo get_template_directory_uri(); ?>/form-contact.php">
<div class="form-group">
<label for="inputNome">Nome Completo *</label>
<input type="text" id="inputNome" name="inputNome" required class="form-control" placeholder="Nome Completo">
</div>
<div class="form-group">
<label for="inputEmail">E-mail *</label>
<input type="email" id="inputEmail" name="inputEmail" required class="form-control" placeholder="Digite seu e-mail">
</div>
<div class="form-group">
<label for="inputTelefone">Telefone</label>
<input type="tel" id="inputTelefone" name="inputTelefone" class="form-control" placeholder="Telefone">
</div>
<div class="form-group">
<label for="inputAssunto">Assunto</label>
<select class="form-control" id="inputAssunto" name="inputAssunto" >
<option disabled selected value> -- Selecione -- </option>
<option value="Orçamento">Orçamento</option>
<option value="Hospedagem">Hospedagem</option>
<option value="Dúvidas">Dúvidas</option>
<option value="Informações">Informações</option>
<option value="Outro">Outro</option>
</select>
</div>
<div class="form-group">
<label for="inputBriefing">Briefing</label>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" id="inputBriefing" name="inputBriefing">
<p class="help-block">Se preferir adicione seus arquivos (.pdf, .docx ou .zip)</p>
</div>
<!--Hpam Sponypot -->
<div class="form-group" style="visibility: hidden">
<label for="address">Address</label>
<input type="text" name="address" id ="address">
<p> Humans, do not fill out this form! </p>
</div>
<div class="form-group">
<label for="inputMensagem">Mensagem *</label>
<textarea class="form-control" rows="3" id="inputMensagem" name="inputMensagem" required placeholder="Escreva sua mensagem"></textarea>
</div>
<p><small>* Campos obrigatórios.</small></p>
<button type="submit" class="btn btn-info">Enviar</button>
</form>
I'm using a shared host on Hostgator.
You were attempting to add the file as a new destination address and not an attachment.
See below for suggested amendment.
//Add attachment
// $_FILES['inputBriefing'] is an array not the file
// adding the file as an attachment before checking for errors is a bad idea also
//$mail->addAttachment($_FILES['inputBriefing']);
if (isset($_FILES['inputBriefing']) && $_FILES['inputBriefing']['error'] == UPLOAD_ERR_OK) {
// this is attempting to add an address to send the email to
//$mail->addAddress($_FILES['inputBriefing']['tmp_name'],$_FILES['inputBriefing']['name']);
$mail->addAttachment($_FILES['inputBriefing']['tmp_name'],
$_FILES['inputBriefing']['name']);
}
You have to add enctype in you form tag like this.
<form id="contact" method="post" action="<?php echo get_template_directory_uri(); ?>/form-contact.php" enctype="multipart/form-data">
Try this form tag

Form validation is not working in my CI project (fixed, code updated)

I am newbie at CodeIgniter. I am trying to implement form validation in user registration.
$autoload['libraries'] = array('database','session','encrypt','form_validation');
$autoload['helper'] = array('url','file','form');
$autoload['model'] = array('user_model');
Controller's Code:
class User_registration extends CI_Controller {
public function index() {
$this->register();
}
function register() {
//set validation rules
$this->load->library('form_validation');
$this->form_validation->set_rules('user_name', 'First Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
$this->form_validation->set_rules('email_id', 'Email ID', 'trim|required|valid_email|is_unique[email_id]');
$this->form_validation->set_rules('user_password', 'Password', 'trim|required|matches[confirm_password]|md5');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|md5');
//validate form input
if ($this->form_validation->run() == FALSE) {
// fails
$data = array();
$data['title'] = 'Registration | Admin Panel';
$data['header_content'] = $this->load->view('adminEntry/header_content', '', true);
$data['footer_content'] = $this->load->view('adminEntry/footer_content', '', true);
$this->load->view('adminentry/user_registration', $data);
} else {
//insert the user registration details into database
echo '<pre>';
print_r($data);
exit();
$data = array(
'user_name' => $this->input->post('user_name'),
'email_id' => $this->input->post('email_id'),
'password' => $this->input->post('user_password'),
);
if ($this->user_model->insertuser($data)) {
if ($this->user_model->sendEmail($this->input->post('email_id'))) {
// successfully sent mail
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
redirect('user_registration');
} else {
// error
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('user_registration');
}
} else {
// error
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('user_registration');
}
}
}
User Model:
class User_model extends CI_Model {
//insert into user table
function insertUser($data) {
return $this->db->insert('user', $data);
}
function sendEmail($to_email) {
$from_email = 'sample#mail.com'; //change this to yours
$subject = 'Verify Your Email Address';
$message = 'Dear User,<br /><br />Please click on the below activation link to verify your email address.<br /><br /> http://example.com/user/verify/' . md5($to_email) . '<br /><br /><br />Thanks<br />Mydomain Team';
//configure email settings
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.example.com'; //smtp host name
$config['smtp_port'] = '465'; //smtp port number
$config['smtp_user'] = $from_email;
$config['smtp_pass'] = 'examplepass'; //$from_email password
$config['mailtype'] = 'html';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$config['newline'] = "\r\n"; //use double quotes
$this->email->initialize($config);
//send mail
$this->email->from($from_email, 'example.com');
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
return $this->email->send();
}
//activate user account
function verifyEmailID($key) {
$data = array('approval_status' => 1);
$this->db->where('md5(email_id)', $key);
return $this->db->update('user', $data);
}
}
View Page:
<div class="container">
<div class="full-content-center animated fadeInDownBig">
<p class="text-center"><img src="<?php echo base_url(); ?>adminAssets/img/login-logo.png" alt="Logo"></p>
<div class="login-wrap">
<div class="row">
<div class="col-sm-6">
<?php echo $this->session->flashdata('verify_msg'); ?>
</div>
</div>
</div>
<div class="login-block">
<?php
$attributes = array("name" => "registrationform");
echo form_open("user_registration/index", $attributes);
?>
<form role="form" method="post" action="<?php echo base_url(); ?>user_registration" enctype="multipart/form-data>">
<div class="form-group login-input">
<i class="fa fa-user overlay"></i>
<input type="text" name="user_name" value="<?php echo set_value('user_name'); ?>" class="form-control text-input" placeholder="Name">
<span class="text-danger"><?php echo form_error('user_name'); ?></span>
</div>
<div class="form-group login-input">
<i class="fa fa-envelope overlay"></i>
<input type="text" name="email_id" value="<?php echo set_value('email_id'); ?>" class="form-control text-input" placeholder="E-mail">
<span class="text-danger"><?php echo form_error('email_id'); ?></span>
</div>
<div class="form-group login-input">
<i class="fa fa-key overlay"></i>
<input type="password" name="user_password" value="<?php echo set_value('user_password'); ?>" class="form-control text-input" placeholder="Password" id="txtNewPassword">
<span class="text-danger"><?php echo form_error('user_password'); ?></span>
</div>
<div class="form-group login-input">
<i class="fa fa-key overlay"></i>
<input type="password" name="confirm_password" value="<?php echo set_value('confirm_password'); ?>" class="form-control text-input" placeholder="Confirm Password" id="txtConfirmPassword" onChange="isPasswordMatch();" >
</div>
<div class="form-group login-input" id="divCheckPassword"></div>
<div class="row">
<div class="col-sm-12">
<button type="submit" name="submit" class="btn btn-default btn-block">Register</button>
</div>
</div>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</form>
</div>
</div>
</div>
</div>
Here is my error:
Error Number: 1146
Table 'counterpressing.email_id' doesn't exist
SELECT * FROM email_id WHERE email_id = 'shakil#gmail.com' LIMIT 1
Filename: D:/Xampp/htdocs/ffbdhub.com/system/database/DB_driver.php
Line Number: 691
Not sure if this has been brought up, but your validation rule isn't quite right... Your "is_unique()" requires the
table and field, so you have the field name which is email_id, but your table name is nowhere to be seen.
So whatever your table name is for your table containing email_id that you are wanting to check against, you need to change this...
$this->form_validation->set_rules('email_id', 'Email ID', 'trim|required|valid_email|is_unique[email_id]');
To this
$this->form_validation->set_rules('email_id', 'Email ID', 'trim|required|valid_email|is_unique[table_name.email_id]');
In simpler terms, you need to have is_unique[table_name.email_id] , where table_name is the name of the table that contains the email_id you are testing for.
I think you have to load database. Like this
$this->load->database() in file.
This might be solve your problem.

PHP Contact Form (PHPMailer)

Fist time using the GitHub PHPMailer and I have an issue with sending emails.
The data seems to be sent to the form and I am lost beyond that.
I know I am not using the errors in my page, which is why for now I am printing them to the php form.
html (index.php)
<form name="contactform" id="myform" class="fs-form fs-form-full" autocomplete="off" method="post" action="send.php">
<ol class="fs-fields">
<li>
<label class="fs-field-label fs-anim-upper" for="q1">What's your name?</label>
<input class="fs-anim-lower" id="q1" name="q1" type="text" placeholder="Johnny Bravo" required/>
</li>
<li>
<label class="fs-field-label fs-anim-upper" for="q2" data-info="We won't send you spam, we promise...">What's your email address?</label>
<input class="fs-anim-lower" id="q2" name="q2" type="email" placeholder="me#email.com" required/>
</li>
<li data-input-trigger>
<label class="fs-field-label fs-anim-upper" for="q3" data-info="This will help us know what kind of service you need">What can we do for you? <span style="font-size:20px;">(select one)</span></label>
<div class="fs-radio-group fs-radio-custom clearfix fs-anim-lower">
<span><input id="q3b" name="q3" type="radio" value="graphic"/><label for="q3b" class="radio-graphic">Graphic Design</label></span>
<span><input id="q3c" name="q3" type="radio" value="web"/><label for="q3c" class="radio-web">Web Design</label></span>
<span><input id="q3a" name="q3" type="radio" value="motion"/><label for="q3a" class="radio-motion">Motion Graphics</label></span>
<span><input id="q3d" name="q3" type="radio" value="other"/><label for="q3d" class="radio-other">Other/More</label></span>
</div>
</li>
<li>
<label class="fs-field-label fs-anim-upper" for="q4">Describe your project in detail.</label>
<textarea class="fs-anim-lower" id="q4" name="q4" placeholder="Describe here"></textarea>
</li>
<li>
<label class="fs-field-label fs-anim-upper" for="q5">What's your budget? (USD)</label>
<input class="fs-mark fs-anim-lower" id="q5" name="q5" type="number" placeholder="1000" step="100" min="100"/>
</li>
</ol><!-- /fs-fields -->
<button class="fs-submit" type="submit" value="Send">Send It</button>
</form><!-- /fs-form -->
PHP (send.php)
<?php
session_start();
require_once 'libs/phpmailer/PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['q1'], $_POST['q2'], $_POST['message'])) {
$fields = [
'q1' => $_POST['q1'],
'q2' => $_POST['q2'],
'q3' => $_POST['q3'],
'q4' => $_POST['q4'],
'q5' => $_POST['q5']
];
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 = 'myemail#gmail.com';
$m->Password = 'mypassword';
$m->SMTPSecure = 'ssl';
$m->Port = 465;
$m->isHTML();
$m->Subject = 'Contact form submitted';
$m->Body = 'From: ' . $fields['q1'] . ' (' . $fields['q2'] . ')<p>Budget</p><p>' . $fields['q5'] . '</p><p>Service</p><p>' . $fields['q3'] . '</p><p>Details</p><p>' . $fields['q4'] . '</p>';
$m->FromName = 'Contact';
$m->AddAddress('myemail#gmail.com', 'Ollie Taylor');
if($m->send()) {
header('Location: thanks.php');
die();
} else {
$errors[] = 'Sorry, could not send email. Try again later.';
}
}
} else {
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: index.php');
Thankyou!
You have some syntax errors for starters.
Line 30 of send.php
$m-Host = 'smtp outgoing here';
Should be
$m->Host = 'smtp outgoing here';
and line 39
$m->Body = 'From:: ' . $fields['q1'] . '(' $fields['q2'] ')' . $fields['q3'] . $fields['q4'] . $fields['q5'];
Should be
$m->Body = 'From:: ' . $fields['q1'] . '(' . $fields['q2'] . ')' . $fields['q3'] . $fields['q4'] . $fields['q5'];
(added concatenation inbetween your parenthesis)
Overall, I'd suggest you look into your PHP error log. I haven't tested it further to see if the email actually sends. But big picture here: Check PHP error log.

Categories