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.
Related
I have created a simple registration/login system with PHP/SQL in MVC pattern.
It works perfectly but I noticed a little bug; when I login with user and email that they are not in my database, I can't never visualize the warning message "These user and email are not in our database". I noticed that in the http bar on the top I visualize the GET request "action="error" ONLY when then I refresh the page, and not when I immediately click the submit button for the fields control. Where is the problem?
Here my login page code:
<h2>Login</h2>
<?php
$login = new MvcTemplate();
$login -> loginUserController();
if(isset($_GET['action'])){
if($_GET['action'] == 'error'){
echo '<div class="alert alert-warning">Ops, these user and email are not in our database!</div>';
}
if($_GET['action'] == 'captchafail'){
echo '<div class="alert alert-warning">Ops, flag the Captcha!</div>';
}
}
?>
<form method="POST">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="La tua Mail" name="mail" required>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="La tua Password" name="password" required>
</div>
<div class="g-recaptcha my-5" data-sitekey="6LdJAwodAAAAALA5PrlYI9n96h5f4AmSab7SOSKC"></div>
<div class="d-grid">
<button type="submit" class="btn btn-primary" name="login">Entra</button>
</div>
</form>
Here the managing of the Login feature in the Controller:
// Gestione della funzione di Login;
public function loginUserController(){
if(isset($_POST['login'])){
// Cifratura della password mediante funzione "crypt";
$securePass = crypt($_POST['password'], '$5$zyPltHmiO9ZqMg7JHRWktNhB_GZ0jiQWvDe0c4N7$');
$dataController = array(
'mail' => $_POST['mail'],
'password' => $securePass
);
$responseDb = Data::loginUserModel($dataController, 'users');
// Controllo di ReCaptcha;
$secret = '6LdJAwodAAAAAOlQKWxeJ2LCydsRpl1M9SrsXqOZ';
$response = $_POST['g-recaptcha-response'];
$remoteIP = $_SERVER['REMOTE_ADDR'];
$verify = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteIP");
$result = json_decode($verify);
if($result -> success){
if($responseDb['email'] == $_POST['mail'] && $responseDb['pass'] == $securePass){
// Inizializzo una sessione;
session_start();
// Creo una variabile di sessione;
$_SESSION['validation'] = true;
header('location:users');
}
}elseif(empty($_POST['g-recaptcha-response'])){
header('location:captchafail');
}
else{
header('location:error');
}
}
}
And here the page links.php in the Model directory:
<?php
class Pages{
public static function showPages($links){
if( $links == 'login' ||
$links == 'users' ||
$links == 'update' ||
$links == 'logout'
){
$moduleNav = 'views/modules/'.$links.'.php';
}elseif($links == 'index'){
$moduleNav = 'views/modules/register.php';
}elseif($links == 'ok'){
$moduleNav = 'views/modules/register.php';
}elseif($links == 'error'){
$moduleNav = 'views/modules/login.php';
}elseif($links == 'captchafail'){
$moduleNav = 'views/modules/login.php';
}elseif($links == 'edit'){
$moduleNav = 'views/modules/users.php';
}else{
$moduleNav = 'views/modules/register.php';
}
return $moduleNav;
}
}
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
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.
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
I am trying to validate a contactform serversite with php and client site with the jQuery validation plugin. First when I use jQuery validation plugin after entering a email adress and I entered # and 1 character after the # the jQuery validation plugin will pass the email adress even without .com, .org, etc. At there demo site you can see what I mean: [http://jqueryvalidation.org/files/demo][1]. Second I have tried to validate the server site with PHP but that doesn't work and I can't find out where it is going wrong. The validation file looks like:
<?php
// We gaan de errors in een array bijhouden
$aErrors = array();
$aErrors ['name'] = '';
$aErrors ['email'] = '';
$aErrors ['message'] = '';
if ('POST' == $_SERVER['REQUEST_METHOD']) {
// Er zijn gegevens verstuurd naar deze pagina!
// Een naam bevat letters en spaties (minimaal 3)
if ( !isset($_POST['name']) or !preg_match( '~^[\w ]{2,}$~', $_POST['name'] ) ) {
$aErrors['name'] = 'Please fill in your name';
}
// Een email-adres is wat ingewikkelder
if ( !isset($_POST['email']) or !preg_match( '~^[a-z0-9][a- z0-9_.\-]*#([a-z0-9]+\.)*[a-z0-9][a-z0-9\-]+\.([a-z]{2,6})$~i', $_POST['email'] ) ) {
$aErrors['email'] = 'Please fill in your e-mail address';
}
// Een adres heeft letters, cijfers, spaties (minimaal 5)
if ( !isset($_POST['message']) or !preg_match( '~^[\w\d ]{5,}$~', $_POST['message'] ) ) {
$aErrors['message'] = 'What would you like to share?';
}
if ( count($aErrors) == 0 ) {
// We hebben alle gegevens
// Gegevens verwerken!
// Volgende pagina aub
header('Location: http://www.phpfreakz.nl/someotherpage.php');
exit();
}
}
?>
The validation.php is required once at the top of the index.php, like:
<?php require_once 'php/validation.php'; ?>
<!doctype html>
<html lang="en" class="no-js">
<head>
<title>Alternate Fixed And Scroll Backgrounds</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
The contact form it self looks like:
<div class="contact">
<div class="formfield">
<form method="post" class="cmxform" id="commentForm" action="php/contact.php">
<div class="fieldset">
<input id="name" name="name" class="error_name" type:"text" placeholder="What is your name?" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '' ?>" />
<div class="error_name"><?php print $aErrors['name'];?></div>
<input id="email" name="email" class="error_email" type="email" placeholder="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '' ?>" />
<div class="error_email"><?php print $aErrors['email'];?></div>
<textarea id="message" name="message" class="error_message" placeholder="message" value="<?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '' ?>" /></textarea>
<div class="error_message"><?php print $aErrors['message'];?></div>
<input name="submit" type="submit" value="Versturen" />
</div>
</form>
</div>
</div>
What am I doing wrong with the PHP validation that it doesn't work. When I remove:
<?php require_once 'php/validation.php'; ?>
I receive an error, so it knows it is there but doesn't do anything with it.
This is how I have changed the contact form. Validation now is placed in front of the PHPmailer. When the contact form is entered correctly the mail is send as it should. But when the form isn't entered correctly and I click submit there will be no error message displayed and I will be transfered to a blanc contact.php page.
So is how contact.php looks:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'PHPMailerAutoload.php';
$aErrors = array();
$aErrors ['name'] = '';
$aErrors ['email'] = '';
$aErrors ['message'] = '';
if ('POST' == $_SERVER['REQUEST_METHOD']) {
// Er zijn gegevens verstuurd naar deze pagina!
// Een naam bevat letters en spaties (minimaal 3)
if ( !isset($_POST['name']) or !preg_match( '~^[\w ]{3,}$~', $_POST['name'] ) ) {
$aErrors['name'] = 'Please fill in your name';
}
// Een email-adres is wat ingewikkelder
if ( !isset($_POST['email']) or !preg_match( '~^[a-z0-9][a- z0-9_.\-]*#([a-z0-9]+\.)*[a-z0-9][a-z0-9\-]+\.([a-z]{2,6})$~i', $_POST['email'] ) ) {
$aErrors['email'] = 'Please fill in your e-mail address';
}
// Een adres heeft letters, cijfers, spaties (minimaal 5)
if ( !isset($_POST['message']) or !preg_match( '~^[\w\d ]{5,}$~', $_POST['message'] ) ) {
$aErrors['message'] = 'What would you like to share?';
}
if ( count($aErrors) == 0 ) {
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'xxxxxxxxxxxxx'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxxx'; // SMTP username
$mail->Password = 'xxxxxxxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->From = 'xxxxxxxxx';
$mail->FromName = $_POST['name'];
$mail->addAddress('x', 'x'); // Add a recipient
// Name is optional
$mail->addReplyTo($_POST['email']);
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Contact formulier';
$mail->Body = $_POST['message'];
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if($mail->send()) {
header('Location: localhost:8888/one_page_redirect kopie 3');
die();
} else {
$errors[] ='Sorry, could not send email. Try again later.';
}
}
} else {
$errors[] = 'Something went wrong.';
}
?>
The contact form looks like:
<div class="contact">
<div class="formfield">
<form action="php/contact.php" method="post" class="cmxform">
<?php
if ( isset($aErrors) and count($aErrors) > 0 ) {
foreach ( $aErrors as $error ) {
print '<div>' . $error . '</div>';
}
}
?>
<div class="fieldset">
<input id="name" class="error_name" name="name" placeholder="What is your name?" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '' ?>" />
<?php if (!empty($aErrors['name'])) { ?><div class="error_name"><?php print $aErrors['name'];?></div><?php } ?>
<input id="email" name="email" placeholder="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '' ?>" />
<?php if (!empty($aErrors['email'])) { ?><div class="error_email"><?php print $aErrors['email'];?></div><?php } ?>
<textarea id="message" class="error_message" name="message" placeholder="message" value="<?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '' ?>" /></textarea>
<?php if (!empty($aErrors['newt_win_messagev(title, button_text, format, args)'])) { ?><div class="error_message"><?php print $aErrors['message'];?></div><?php } ?>
<input name="submit" type="submit" value="Versturen" />
</div>
</form>
</div>
</div>
Thanx in advance.
For server side I use:
if (!filter_var($value, FILTER_VALIDATE_EMAIL))
{
// Not Valid
}
For client side validation check out: Email validation using jQuery