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.
Related
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>
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
My PHPMailer script works fine on xampp local server.But on my website that is located on a apache server isn't working.I think in my apache server doesn't finds the right location of phpMailerAutoload.php but I'm not sure.
I'll be very thankfull if someone can help me with this .
EDIT:When I press the "send" button it displays the error that i set up to display in my PhpMailer script.(the last else)
My PHPMailer script:
<?php
session_start();
require_once 'phpMailer/PHPMailerAutoload.php';
$errors= [];
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
$fields=[
'name'=>$_POST['name'],
'email'=>$_POST['email'],
'message'=>$_POST['message']
];
foreach($fields as $field => $data){
if(empty($data)){
$errors[]='Il <b>' . $field . '</b> è necessario.';
}
}
if(isset($_POST['tel'])){
$sec_fields=[
'tel'=>$_POST['tel']
];
}
/*------Validation--------*/
if(!empty($_REQUEST['name'])){
$name = $_REQUEST['name'];
if(!preg_match("/^[a-zA-Z'-]+$/",$name)){
$errors[]='Il <b>nome</b> non è valido.';
}
}
if(!empty($_REQUEST['email'])){
$email = $_REQUEST['email'];
$valid = filter_var($email, FILTER_VALIDATE_EMAIL);
if($valid == false){
$errors[]='L\'indirizzo <b>email</b> non è valido.';
}
}
/*------Creating PHPMailer Class-------*/
if(empty($errors)) {
$m= new PHPMailer;
$m -> isSMTP();
$m -> SMTPAuth = true;
$m->Host = 'wolf.dnshigh.com';
$m->Username = 'email#danadesign.it';
$m->Password = 'password';
$m->SMTPSecure = 'ssl';
$m->Port = 465;
$m->isHTML();
$m->Subject = 'Avete ricevuto un nuovo messaggio .' ;
$m->Body =' Inviato da : ' . $fields['name'] . ' (' .$fields['email'] . ') <br><br> <p>' . $fields['message'] . '<br><br> </p> <p>Telefono: ' . $sec_fields['tel'] . '</p>' ;
$m->FromName = 'DanaDesign Mail';
$m->AddAddress ('MyinboxEmail#yahoo.it', 'My name');
/*-----Sending Email------*/
if ($m->send()) {
header('Location: redirect.html');
die();
} else {
$errors[]='Siamo spiacenti,non siamo riusciti a inviare il messaggio.Si prega di riprovare più tardi.';
}
}
} else {
$errors[]='Qualcosa è andato storto.';
}
header('Location: contact.php');
$_SESSION['errors']= $errors;
$_SESSION['fields']= $fields;
$_SESSION['sec_fields']= $sec_fields;
?>
And my contact form:
<section>
<h2>Write us a message</h2>
<div class="contact">
<?php if(!empty($errors)): ?>
<div class="panel">
<ul><li> <?php echo implode('</li><li> ',$errors); ?> </li></ul>
</div>
<?php endif; ?>
<form method="post" action="contact-script.php">
<label>
<img src="img/person.png" alt="Person Icon"> Nome*
<input type="text" name="name" autocomplete="off" <?php echo isset($fields['name']) ? 'value="' . e($fields['name']) . '"' : '' ?> />
</label>
<label>
<img src="img/telephone.png" alt="Telephone Icon"> Telefono
<input type="text" name="tel" autocomplete="off" <?php echo isset($sec_fields['tel']) ? 'value="' . e($sec_fields['tel']) . '"' : '' ?> />
</label>
<label>
<img src="img/mail.png" alt="Mail Icon">Indirizzo email*
<input type="text" name="email" autocomplete="off" <?php echo isset($fields['email']) ? 'value="' . e($fields['email']) . '"' : '' ?> />
</label>
<label>
<img src="img/message.png" alt="Message Icon">Messaggio*
<textarea name="message" cols="20" rows="2"> <?php echo isset($fields['message']) ? e($fields['message']) : '' ?> </textarea>
</label>
<input type="submit" value="Invia" />
</form>
</div>
</section>
Some text is in Italian language , I'm sorry about that.
I have a script and it runs very well, but I want know how to echo an error div if recaptcha isn't confirmed. In this script if recaptcha wasn't confirmed the page will reload and nothing will be send to my mail, but I don't know how to display an error that tells the user: "You must verificate that you aren't a robot".
Can you help me?
CODE:
<?php
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"../support/style/contactform.css\">\n";
$emailpattern="^[^# ]+#[^# ]+\.[^# \.]+$";
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<form method="post" id="contactformall">
<p>Nome</p>
<input type="text" name="name" class="contactformimput"/>
<p>Email (obbligatorio)</p>
<input type="text" name="email" class="contactformimput"/>
<p>Numero</p>
<input type="text" name="number" class="contactformimput"/>
<p>Messaggio (obbligatorio)</p>
<input type="text" name="message" onkeyup="adjust_textarea(this)" class="contactformimput" id="contactformtext">
<div class="g-recaptcha" data-sitekey="____key____"></div>
<div id="divcontactbutton">
<input type="reset" name="send" value="Resetta" class="button" id="resetmessage"/>
<input type="submit" name="send" value="Invia Messaggio" class="button" id="sendmessage"/>
</div>
</form>';
exit;
}
$responsejson=file_get_contents("google.com/recaptcha/api/…);
$response = json_decode($responsejson);
if($response->success==false) { echo "<div class=\"emailerror\" id=\"emailnoninviata\"><div><span>•</span> Email non inviata</div></div>";
**/////THIS part DON'T RUN**
}else
{
if (isset($_POST['send'])) {
if(!ereg($emailpattern,$_POST['email'])) {
$emailerror = true;
echo "<div class=\"emailerror\"><div><span>6</span> Email non valida</div></div>";
} if ($_POST['message'] == "") {
$emailerror = true;
echo "<div class=\"emailerror\"><div><span>6</span> Inserisci un messaggio</div></div>";
} elseif ($_POST['message'] != "" and ereg($emailpattern,$_POST['email'])){
$emailerror = false;
};
if ($emailerror == true) {
echo '<form method="post">
<p>Nome</p>
<input type="text" name="name" class="contactformimput"/>
<p>Email*</p>
<input type="text" name="email" class="contactformimput"/>
<p>Numero</p>
<input type="text" name="number" class="contactformimput"/>
<p>Messaggio*</p>
<input type="text" name="message" onkeyup="adjust_textarea(this)" class="contactformimput" id="contactformtext">
<div class="g-recaptcha" data-sitekey="___KEY___"></div>
<div id="divcontactbutton">
<input type="reset" name="send" value="Resetta" class="button" id="resetmessage"/>
<input type="submit" name="send" value="Invia Messaggio" class="button" id="sendmessage"/>
</div>
</form>';
}
if (isset($_POST['send']) and $emailerror == false) {
$to = "mail#gmail.com";
$subject = "B&B";
$user_name = 'Name: ' . $_POST['name'] . "\n";
$user_email = 'Email: ' . $_POST['email'] . "\n";
$user_ip = 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n";
$user_message = 'Message: ' . $_POST['message'];
$message = $user_name . $user_email . $user_ip . $user_message;
$success = mail($to, $subject, $message);
echo "<div class=\"emailerror\" id=\"emailinviata\"><div> <span>5</span> Email inviata correttamente</div></div>";}
}
}
?>
You are mixing javascript code with php code. Javascripts uses '.' to access class vars/functions, php uses '->'.
Please read this page in order to use Recaptcha with php: https://developers.google.com/recaptcha/old/docs/php
The recaptcha documentation shows that this API request should return JSON. You will need to decode the JSON response to refer to its contents. So do this after you use file_get_contents() to get the response:
$response = json_decode($response);
and then you should be able to check for success with a little adjustment to your syntax.
if($response->success==false)
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