CAPTCHA existing and working but not active on contact form - javascript

i'm trying to add IconCaptcha (https://github.com/fabianwennink/IconCaptcha-Plugin-jQuery-PHP#installation) to a contact form.
I managed to implement it with success on the web page. But whenever i hit the SUBMIT button (with the other fields well filled) the form is sent. Even if i hit the wrong captcha... Or no captcha at all.
Here is the contact.php page code :
<?php
session_start();
require('IconCaptcha-PHP/src/captcha-session.class.php');
require('IconCaptcha-PHP/src/captcha.class.php');
IconCaptcha::setIconsFolderPath('../assets/icons/');
IconCaptcha::setIconNoiseEnabled(true);
if(!empty($_POST)) {
if(IconCaptcha::validateSubmission($_POST)) {
$captchaMessage = 'Le message a bien été envoyé!';
} else {
$captchaMessage = json_decode(IconCaptcha::getErrorMessage())->error;
}
}
?>
<!doctype html>
<!--
* IconCaptcha Plugin: v2.5.0
* Copyright © 2017, Fabian Wennink (https://www.fabianwennink.nl)
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
-->
<html>
<head>
<!--FORMAT-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!--STYLES-->
<link href="css/styles.css" rel="stylesheet" type="text/css">
<link href="css/bootstrap-4.3.1.css" rel="stylesheet" type="text/css">
<!-- IconCaptcha stylesheet -->
<link href="IconCaptcha-PHP/assets/css/icon-captcha.min.css" rel="stylesheet" type="text/css">
<script src="http://use.edgefonts.net/montserrat:n4:default.js" type="text/javascript"></script>
<!--SCRIPTS BOOTSTRAP-->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap-4.3.1.js"></script>
<body>
<section id="contact" class="section-orange">
<div class="container-fluid" justify-content="center" style="width: 90%">
<!-- DEBUT FORMULAIRE CONTACT -->
<?php
if(isset($captchaMessage)) {
echo '<b>Captcha Message: </b>' . $captchaMessage;
}
?>
<form id="reused_form" role="form" method="post" action="envoiformulaire.php">
<div class="row">
<div class="col-md-6 form-group">
<label for="first_name"></label>
<input id="firstname" name="first_name" type="text" class="form-control" placeholder="Prénom" required="required">
</div>
<div class="col-md-6 form-group">
<label for="last_name"></label>
<input id="lastname" name="last_name" type="text" class="form-control" placeholder="NOM" required="required">
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<label for="email"></label>
<input id="email" name="email" type="email" class="form-control" placeholder="Courriel" required="required">
</div>
<div class="col-md-6 form-group">
<label for="telephone"></label>
<input id="telephone" type="tel" name="telephone" onkeyup="formatte(this,2)" onkeypress="return isNumberKey(event)" class="form-control" placeholder="Téléphone" required="required" minlength="14" maxlength="14">
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="comments"></label>
<textarea id="message" name="comments" class="form-control" placeholder="Message (400 caractères maximum)" maxlength="400" rosws="4" required="required"></textarea>
</div>
<div class="col-md-12 form-group">
<div class="captcha-holder"></div>
</div>
<div class="col-md-12 form-group">
<br> <input type="submit" id="btnContactUs" class="btn btn-success btn-send" value="Envoyer le message">
</div>
</div>
</form>
<script src="IconCaptcha-PHP/assets/js/icon-captcha.min.js" type="text/javascript"></script>
<!-- Initialize the IconCaptcha -->
<script async type="text/javascript">
$(window).ready(function() {
$('.captcha-holder').iconCaptcha({
theme: ['light'],
fontFamily: '',
clickDelay: 500,
invalidResetDelay: 3000,
requestIconsDelay: 1500,
loadingAnimationDelay: 1500, // How long the fake loading animation should play.
hoverDetection: true,
showCredits: 'show',
enableLoadingAnimation: false,
validationPath: 'IconCaptcha-PHP/src/captcha-request.php',
messages: {
header: "Vous devez choisir, « …but, choose wiesly! »",
correct: {
top: "« You have chosen… wisely. »",
bottom: "Félicitations! Vous n'êtes pas un robot."
},
incorrect: {
top: "« You chose poorly! »",
bottom: "Oups! Mauvaise image."
}
}
})
.bind('init.iconCaptcha', function(e, id) {
console.log('Event: Captcha initialized', id);
}).bind('selected.iconCaptcha', function(e, id) {
console.log('Event: Icon selected', id);
}).bind('refreshed.iconCaptcha', function(e, id) {
console.log('Event: Captcha refreshed', id);
}).bind('success.iconCaptcha', function(e, id) {
console.log('Event: Correct input', id);
}).bind('error.iconCaptcha', function(e, id) {
console.log('Event: Wrong input', id);
});
});
</script>
<!-- FIN FORMULAIRE CONTACT -->
</div>
</section>
</body>
</html>
Here is the PHP function envoiformulaire.php to send the form :
<?php
header('Content-Type: text/html; charset=utf-8');
if(isset($_POST['email'])) {
$email_to = "mail#mail.com";
$email_subject = "Nouveau message web";
function died($error) {
echo "Oups! Une ou plusieurs erreurs se trouvent dans votre formulaire.<br>";
echo $error."<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('Oups! Un problème est survenu avec votre formulaire.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp ='/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'Le courriel saisi ne semble pas valide.<br />';
}
$phone_exp = "/^(\d\d\s){4}(\d\d)$/";
if(!preg_match( $phone_exp,$telephone)) {
$error_message .= 'Le numéro de téléphone saisi ne semble pas valide.<br />';
}
$string_exp = "/^[A-Za-z àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ.'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'Le prénom saisi ne semble pas valide.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'Le nom saisi ne semble pas valide.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'Le message saisi ne semble pas valide.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Ci-après le formulaire complété.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Prénom: ".clean_string($first_name)."\n";
$email_message .= "NOM: ".clean_string($last_name)."\n";
$email_message .= "Courriel: ".clean_string($email_from)."\n";
$email_message .= "Téléphone: ".clean_string($telephone)."\n";
$email_message .= "Message: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'Content-Type: text/plain; charset="utf-8"'.
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
My guess is that on the contact page when i hit the SUBMIT button it activates the PHP to send the form without the CAPTCHA (method=post action="envoiformulaire.php").
I may have to add "something" to make the SUBMIT button available only with the captcha completed. But i haven't figured how to do it.
Could someone give me a hint ?
Best regards,
Frédéric.

I was in contact with the creator of icon captcha. He helped me a lot, actually more than i expected.
First mistake, i put a part of the PHP validation code page on the contact form :
if(!empty($_POST)) {
if(IconCaptcha::validateSubmission($_POST)) {
$captchaMessage = 'Le message a bien été envoyé!';
} else {
$captchaMessage = json_decode(IconCaptcha::getErrorMessage())->error;
}
}
It should to go from contact.php to envoiformulaire.php .
After that he helped me with my numbnuts php skills...
On the top of the contact page, the following code should be added :
<?php
session_start();
require('IconCaptcha-PHP/src/captcha-session.class.php');
require('IconCaptcha-PHP/src/captcha.class.php');
IconCaptcha::setIconsFolderPath('../assets/icons/');
IconCaptcha::setIconNoiseEnabled(true);
?>
And add this code (ADD) in the envoiformulaire.php :
<?php
session_start(); // ADD THIS
header('Content-Type: text/html; charset=utf-8');
require('IconCaptcha-PHP/src/captcha-session.class.php'); // ADD THIS
require('IconCaptcha-PHP/src/captcha.class.php'); // ADD THIS
IconCaptcha::setIconsFolderPath('../assets/icons/'); // ADD THIS
IconCaptcha::setIconNoiseEnabled(true); // ADD THIS
if(isset($_POST['email'])) {
$email_to = "mail#mail.com";
$email_subject = "Nouveau message web";
function died($error) {
echo "Oups! Une ou plusieurs erreurs se trouvent dans votre formulaire.<br>";
echo $error."<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('Oups! Un problème est survenu avec votre formulaire.');
}
// ADD THIS
if(!IconCaptcha::validateSubmission($_POST)) {
died('ADD YOUR ERROR MESSAGE HERE');
}
...
And now, it works great, thank you Fabian !
I hope this post will help someone in the futur.
Frédéric.

Related

Failed to load resource: the server responded with a status of 404 (Not Found) on contact form using Js, ajax, php

I am getting the error Failed to load resource: the server responded with a status of 404 (Not Found) and not really sure why it is happening. I have checked the routes and access of the files and everything seems fine.
My Js file looks like this:
var clContactForm = function() {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('.submit-loader');
$.ajax({
type: "POST",
url: "../inc/sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.slideDown("slow");
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.slideUp("slow");
$('.message-warning').fadeOut();
$('#contactForm').fadeOut();
$('.message-success').fadeIn();
}
// There was an error
else {
sLoader.slideUp("slow");
$('.message-warning').html(msg);
$('.message-warning').slideDown("slow");
}
},
error: function() {
sLoader.slideUp("slow");
$('.message-warning').html("Algo ocurrió. Por favor, inténtalo de nuevo");
$('.message-warning').slideDown("slow");
}
});
}
});
};
My php code looks like this:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'myemail#gmail.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Por favor, coloca tu nombre.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Por favor, pon un correo válido.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Por favor, coloca tu mensaje";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Oops! Algo ocurrió, por favor inténtalo de nuevo."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
And finally, my HTML code is this one:
<div class="row section-header" data-aos="fade-up">
<div class="col-full">
<h1 class="display-2 display-2--light">Cuéntanos un poco más de tí para que empieces a vivir la experiencia Tech Consultant</h1>
</div>
</div>
<div class="row contact-content" data-aos="fade-up">
<div class="contact-primary">
<h3 class="h6">Envíanos un mensaje</h3>
<form name="contactForm" id="contactForm" method="post" action="/index.html" novalidate="novalidate">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Nombre" value="" minlength="2" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Asunto" value="" class="full-width">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="¿Qué es lo que más te interesa de Tech Consultant?" rows="10" cols="50" required="" aria-required="true" class="full-width"></textarea>
</div>
<div class="form-field">
<button class="full-width btn--primary">Enviar</button>
<div class="submit-loader">
<div class="text-loader">Enviando...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form>
<!-- contact-warning -->
<div class="message-warning">
¡Algo ocurrió! Por favor, intenta de nuevo.
</div>
<!-- contact-success -->
<div class="message-success">
¡Hemos recibido tu mensaje! Nuestros asesores se pondrán en contacto contigo<br>
</div>
</div> <!-- end contact-primary -->
As I mentioned before, I am getting the Failed to load resource: the server responded with a status of 404 (Not Found) error and I am not really sure why. If you can give me some insight, that would be amazing!
Thank you in advance for all of your help!!
I did some changes to your code
yes that code was not working
i sorted the same on my localhost
Please compare the code:
Updated code: ( Html and js code)
$(document).ready(function () {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('.submit-loader');
$.ajax({
type: "POST",
url: "process.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.slideDown("slow");
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.slideUp("slow");
$('.message-warning').fadeOut();
$('#contactForm').fadeOut();
$('.message-success').fadeIn();
}
// There was an error
else {
sLoader.slideUp("slow");
$('.message-warning').html(msg);
$('.message-warning').slideDown("slow");
}
},
error: function() {
sLoader.slideUp("slow");
$('.message-warning').html("Algo ocurrió. Por favor, inténtalo de nuevo");
$('.message-warning').slideDown("slow");
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<div class="row section-header" data-aos="fade-up">
<div class="col-full">
<h1 class="display-2 display-2--light">Cuéntanos un poco más de tí para que empieces a vivir la experiencia Tech Consultant</h1>
</div>
</div>
<div class="row contact-content" data-aos="fade-up">
<div class="contact-primary">
<h3 class="h6">Envíanos un mensaje</h3>
<form name="contactForm" id="contactForm" method="post" novalidate="novalidate">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Nombre" value="" minlength="2" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Asunto" value="" class="full-width">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="¿Qué es lo que más te interesa de Tech Consultant?" rows="10" cols="50" required="" aria-required="true" class="full-width"></textarea>
</div>
<div class="form-field">
<button class="full-width btn--primary">Enviar</button>
<div class="submit-loader">
<div class="text-loader">Enviando...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form>
<!-- contact-warning -->
<div class="message-warning">
¡Algo ocurrió! Por favor, intenta de nuevo.
</div>
<!-- contact-success -->
<div class="message-success">
¡Hemos recibido tu mensaje! Nuestros asesores se pondrán en contacto contigo<br>
</div>
</div> <!-- end contact-primary -->
**Php Updated code**
<?php
// Replace this with your own email address
$siteOwnersEmail = 'your email id';
if($_POST) {
$message = "";
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
$error = array();
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Por favor, coloca tu nombre.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Por favor, pon un correo válido.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Por favor, coloca tu mensaje";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
//ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Oops! Algo ocurrió, por favor inténtalo de nuevo."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Let me know if you need zip for running code will send you the same:
enter image description here
You may want to try postman to post a form data instead of using a browser. If you do that, you can find out if your PHP code works fine or not, then focus on the JavaScript code.

javascript function is supposed to display php SESSION data but isn't called

I'm trying to make a regular old registration form for a website; and I'm trying to display the name of the logged-in user(if any) at the top of the page. However, the function that is supposed to update that field doesn't seem o be called at all, and I can't make heads or tails of it, nor of the error messages my console displays:
"Uncaught SyntaxError: Unexpected token < -- pagina_registrazione.php:36"
"Uncaught ReferenceError: update_name is not defined
onload -- pagina_registrazione.php:10"
here is the code:
<?php
require './config_db.php';
?>
<!DOCTYPE HTML>
<html lang = "it" >
<head>
<meta charset="utf-8">
<meta name = "keywords" content = "catcher, profilo, registrazione, utente">
<meta name="author" content="Luca Ballarati">
<link rel="stylesheet" href="./../stile/sottopagine.css" type="text/css" media="screen">
<title>pagina di registrazione</title>
</head>
<body onload=update_name>
<section>
<p id="spia_connessione">NOMEUTENTEQUI</p>
<p>Se hai già un'account <strong>clicca qui</strong> per accedere.</p>
<p>Altrimenti <strong>registrati</strong> compilando i campi qui sotto</p>
</section>
<div id="login_form">
<form name="registra" action="./pagina_registrazione.php" method="post">
<div>
<label><p>Nome Utente</p></label>
<input type="text" placeholder="nome_utente" name="username" required autofocus>
</div>
<div>
<label><p>Password</p></label>
<input type="password" placeholder="password" name="password" required>
</div>
<div>
<label><p>Conferma Password</p></label>
<input type="password" placeholder="conferma_password" name="passwordconfirm" required>
</div>
<input name="pulsante_invio" type="submit" value="Invia">
<?php
if(isset($_POST['pulsante_invio'])) {
$nomeutente = $_POST['username'];
$password = $_POST['password'];
$cpassword = $_POST['passwordconfirm'];
if ($password==$cpassword) {
$query = "SELECT * FROM utenti WHERE NomeUtente='$nomeutente'";
$esegui_query = mysqli_query($con,$query);
if(mysqli_num_rows($esegui_query)>0) {
echo '<script type="text/javascript">
window.alert("Nome Utente già usato: registrarsi con un diverso Nome Utente");
</script>';
}
else {
$query = "INSERT INTO utenti (NomeUtente,Password,Record,Partite)
VALUES('$nomeutente','$password',0,0)";
$esegui_query = mysqli_query($con,$query);
if ($esegui_query) {
$nome = $_SESSION['username'];
//porta l'utente alla pagina di login
echo '<script type="text/javascript">
window.alert("Utente registrato correttamente");
</script>';
//echo '<script type="text/javascript">
//document.getElementById("spia_connessione").innerHTML = "'$nome'";
//</script>';
}
else {
echo '<script type="text/javascript">
window.alert("Errore durante la registrazione");
</script>';
}
}
}
else {
echo '<script type="text/javascript">
window.alert("Password e Password di conferma devono essere uguali");
</script>';
}
}
?>
</form>
</div>
<script type="text/javascript">
function update_name() {
window.alert("nome utente aggiornato");
var nm = <?php echo $_SESSION['username']; ?>;
document.getElementById("spia_connessione").innerHTML = nm;
}
</script>
</body>
Please write this code on the top of your php file.
<?php
ob_start();
session_start();
?>

Ajax-submitted form is not being saved to the database

I have a form with different inputs. On submit i use Ajax to send the data to a MySQL table. If the inputs are blank the jQuery validate plugin stops the submit action.
The POST submit works because i use Firebug and the response Ajax tells me that; but the data doesn't save in my database.
I don't know which part is causing the problem because in JS it doesn't tell me any issue.
My HTML/JS code looks like this:
$(document).ready(function() {
$("#ok").hide();
$("#formula").validate({
rules: {
nombre: {required: true},
mail: {required: true},
estado: {required: true},
imagen: {required:true,
extension:'jpeg|png|jpg|gif'},
checa:{required:true}
},
messages: {
nombre: "Debe introducir su nombre.",
mail:"Introduce una dirección de e-mail válido.",
estado : "Debes seleccionar tu estado donde resides.",
imagen : "Selecciona una imagen válida, jpg, jpeg, png o gif.",
checa: "Debes aceptar los terminos de uso y la política de privacidad"
},
submitHandler: function(form){
var dataString = 'nombre='+ nombre
+ 'mail=' + mail
+ '&estado=' + estado
+ '&imagen=' + imagen
+ '&checa=' + checa
$("#ok").show();
$.ajax({
type: "POST",
url:"envia.php",
data: dataString,
success: function(msg){
$("#ok").html("<strong>Mensaje enviado existosamente, nos pondremos en contacto a la brevedad.</strong>");
document.getElementById("nombre").value="";
document.getElementById("mail").value="";
document.getElementById("estado").value="";
document.getElementById("imagen").value="";
document.getElementById("checa").value="";
setTimeout(function() {$('#ok').fadeOut('fast');}, 3000);
}
});
}
});
});
<section class="wrapper">
<form method="post" name="formulario" id="formula" enctype="multipart/form-data">
<div id="ok"></div>
<label>Nombre:</label>
<input type="text" name="nombre" id="nombre" />
<label>Email:</label>
<input type="email" name="mail" id="mail" />
<label>Estado:</label>
<!--<div class="styled-select">-->
<select name="estado" id="estado">
<option value="">Selecciona tu estado:</option>
<option>Aguascalientes</option>
<option>Baja California</option>
<option>Baja California Sur</option>
<option>Campeche</option>
<option>Chiapas</option>
<option>Chihuahua</option>
<option>Coahuila</option>
<option>Colima</option>
<option>Distrito Federal</option>
<option>Durango</option>
<option>Guanajuato</option>
<option>Guerrero</option>
<option>Hidalgo</option>
<option>Jalisco</option>
<option>México</option>
<option>Michoacán</option>
<option>Morelos</option>
<option>Nayarit</option>
<option>Nuevo León</option>
<option>Oaxaca</option>
<option>Puebla</option>
<option>Querétaro</option>
<option>Quintana Roo</option>
<option>San Luis Potosí</option>
<option>Sinaloa</option>
<option>Sonora</option>
<option>Tabasco</option>
<option>Tamaulipas</option>
<option>Tlaxcala</option>
<option>Veracruz</option>
<option>Yucatán</option>
<option>Zacatecas</option>
</select>
<!--</div>
<div id="file">Chose file</div>-->
<input type="file" name="imagen" id="imagen" class="upload" />
<input type="checkbox" name="checa" id="checa" value="Acepto">Acepto los terminos y condiciones y la politica de privacidad
<input name="URLBack" type="hidden" id="URLBack" value="<?php echo "hhtp://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" />
<input name="input" id="enviar" type="submit" value="Enviar" />
</form>
</section>
And my PHP file looks like this:
include 'conexion.php';
$con = conexion();
$nombre=substr($_POST['nombre'],0,2);
$sql= "SELECT MAX(id) FROM base_de_datos";
$rs=mysql_query($sql);
if(isset($rs) && mysql_num_rows($rs)>0)
{
$row=mysql_fetch_row($rs);
$num=$row;
mysql_free_result($rs);
}
$tumb = implode($num);
$sumando = $tumb + 1;
if ($_FILES["imagen"]["error"] > 0){
echo "ha ocurrido un error";
} else {
$permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
$limite_kb = 2000;
if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 2048){
$ruta = "imagenes/" . $_FILES['imagen']['name'];
if (file_exists($ruta)){
echo $_FILES['imagen']['name'] . ", este archivo existe";
}
else{
$temp = explode(".", $_FILES["imagen"]["name"]);
$newfilename = 'contest'. $sumando . '.' . end($temp);
move_uploaded_file($_FILES["imagen"]["tmp_name"], "imagenes/" . $newfilename);
}
}
}
$caracteres = "AABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
$numerodeletras=10;
$cadena = "";
for($i=0;$i<$numerodeletras;$i++)
{
$cadena .= substr($caracteres,rand(0,strlen($caracteres)),1);
}
$serie=$nombre.$sumando;
$este= date("Y/m/d");
echo $serie;
$_GRABAR_SQL = "INSERT INTO base_de_datos (nombre,email,estado,imagen,condiciones_de_uso,clave,fecha) VALUES ('$_POST[nombre]','$_POST[mail]','$_POST[estado]','$newfilename','$_POST[checa]','$serie','$este')";
mysql_query($_GRABAR_SQL);
$query=mysql_insert_id();
$headers = "MIME-Version: 1.0\r \n";
$headers .= "Content-type: text/html; charset=utf-8 \r \n";
$headers .= "Return-Path: ".$_POST['nombre']." <".$_POST['mail']."> \r \n";
$headers .= "From: OMA Plaza <noreply#example.com> \r \n";
$headers .= "Reply-To: ".$_POST['nombre']." <".$_POST['nombre']."> \r \n";
$headers .= "X-Priority: 1\r\n";
$mail = mysql_real_escape_string($_POST['mail']);
if ( function_exists( 'mail' ) )
{
echo 'mail() is available';
}
else
{
echo 'mail() has been disabled';
}
$asunto = "";
$confir = "Su mensaje fue enviado exitosamente, nos pondremos en contacto con usted a la brevedad";
$mensage = "---------------------------------- \n";
$mensage.= " Contacto \n";
$mensage.= "---------------------------------- \n";
$mensage.= "Nombre: ".$_POST['nombre']."\n";
$mensage.= "Clave Confirmación: ".$serie."\n";
$mensage.= "Email: ".$_POST['mail']."\n";
mail ($mail, $asunto, $mensage, $headers);

Form should not reload

I built a Feedback form with PHP. There is a Popup from Foundation 5 included.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style type="text/css">
.auto-style1 {
margin-left: 1px;
}
.auto-style2 {
margin-left: 0px;
}
.auto-style3 {
text-align: center;
}
.auto-style4 {
text-align: center;
font-size: x-large;
}
.auto-style5 {
color: #FF0000;
}
.auto-style6 {
color: #000000;
}
.auto-style7 {
text-align: left;
}
</style>
<title>Rating</title>
<!-- Sterne Scripts -->
<script src='jquery.js' type="text/javascript"></script>
<script src='jquery.MetaData.js' type="text/javascript" language="javascript"></script>
<script src='jquery.rating.js' type="text/javascript" language="javascript"></script>
<!-- Popup Scripts -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/foundation.css">
<!-- If you are using the gem version, you need this only -->
<link rel="stylesheet" href="css/app.css">
<script src="js/vendor/modernizr.js"></script>
<link rel="stylesheet" href="css/app.css">
<script src="js/vendor/modernizr.js"></script>
<link href='jquery.rating.css' type="text/css" rel="stylesheet"/>
</head>
<body style="background-image: url('img/body-bg.jpg')">
<?php
$send = false;
$error = $text = '';
if ($_SERVER['REQUEST_METHOD'] === "POST") {
$to = 'kontakt#schoenholz.eu';
$subject = "Feedback vom ".date("d.m.Y");
$antispam = $_POST['access'];
$name = $_POST['star1'];
$select = $_POST['Select'];
$text = $_POST['TextArea1'];
$message = "Bewertung: ".$name. "\r\n" . "Warum die Bewertung?: " .$text . "\r\n" . "Woher kennen Sie uns?: " .$select;
$success = true;
if ($antispam != 'irregeheim') {
$success = false; //Fehlerflag setzen
$error .= 'Kein Spam erwünscht!<br>'; // Fehlertext
}
if ($name == '') {
$success = false;
$error .= '"<em>Wie bewerten Sie uns</em>" wurde nicht ausgefüllt';
}
if ($select == "- Bitte auswählen -") {
$success = false; //Fehlerflag setzen
$error .= '<br>"<em>Wie haben Sie uns gefunden</em>" wurde nicht ausgefüllt</br>'; // Fehlertext
}
// ist alles ok ? dann senden
if($success === true) {
if (#mail($to,$subject,$message)) {
$send = true;
echo 'Danke für Ihr Feedback!';
} else {
$error .= 'Ihr Feedback konnte leider nicht gesendet werden. Bitte versuchen sie es später erneut';
}
}
}
if ($send === false) {
?>
Feedback<br/>
<div id="firstModal" class="reveal-modal small" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="auto-style4" style="width: 477px"><strong>Feedback </strong></p>
<p class="auto-style7" style="width: 477px">Bitte füllen Sie alle mit
<span class="auto-style6">*</span> gekennzeichneten Felder aus</p>
<label id="Label1"></label>
<fieldset style="width: 476px"><legend>Wie bewerten Sie uns?
<span class="auto-style5">*</span></legend>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Sehr schlecht") echo "checked";?> value="Sehr schlecht"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Schlecht") echo "checked";?> value="Schlecht"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Durchschnittlich") echo "checked";?> value="Durchschnittlich"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Gut") echo "checked";?> value="Gut"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Hervorragend") echo "checked";?> value="Hervorragend"/> </fieldset>
<p style="height: 36px"> Grund Ihrer Bewertung?</p>
<textarea class="auto-style1" name="TextArea1" style="width: 505px; height: 105px"><?php echo htmlspecialchars($text, ENT_QUOTES);?></textarea>
<p>Wie haben Sie uns gefunden? <span class="auto-style5">*</span></p>
<p>
<select name="Select" style="width: 151px">
<option <?php if($select== "- Bitte auswählen -") echo "selected"; ?>>- Bitte auswählen -</option>
<option <?php if($select== "Familie/Freunde") echo "selected"; ?>>Familie/Freunde</option>
<option <?php if($select== "Suchmaschinen (Google etc.)") echo "selected"; ?>>Suchmaschinen (Google etc.)</option>
<option <?php if($select== "Zeitungen") echo "selected"; ?>>Zeitungen</option>
<option <?php if($select== "Örtliche") echo "selected"; ?>>Örtliche</option>
<option <?php if($select== "Werbung") echo "selected"; ?>>Werbung</option>
<option <?php if($select== "Sonstiges") echo "selected"; ?>>Sonstiges</option>
</select>
</p>
<input type="hidden" name="access" value="irregeheim">
<p class="auto-style3" style="width: 498px">
<input class="auto-style2" name="Submit1" type="submit" value="Senden"></p>
</form>
<?php
}
if (!empty($error)) {
echo $error;
}
?>
<a class="close-reveal-modal" aria-label="Close">×</a>
</div>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>
The problem is that if I push the Feedback button and miss a field, the page reloads and I have to push the Feedback Button again. I already figured out that I have to use ajax and Javascript to handle this but I dont know how I should rewrite my script so it works. Can somebody help me with that?
I use this approach:
1) Create the form on html and put an id on each input element, then I put a span or something to display error message, like this:
<input type="text" name="email" id="email">
<span id="email-message" class="hidden"></span>
2) On your php script, you need to create an array, validate each input and send json data. My array looks like this:
$data = array(
'message' => null,
'form' => array(
'has_errors' => false, // put true if there are input errors
'email' => array(
error => false,
message => null
);
);
);
header("Content-Type: application/json");
echo json_encode($data);
exit;
on this way, you add inputs to $data['form'] as you need. $data['message'] it's a general error like 'Impossible to save now. Try again'.
3) And finally, on your javascript file on success method (after json request to validate form), you check if "data.message" has a general error and if not you use a for each of the data.form to check each input and show the error message if it's necessary:
$('#my-form').on("submit", function(event){
event.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr("action"),
type: 'POST',
data: $form.serialize(),
dataType: 'json',
cache: false
}).done(function(data) {
if(data.message) {
// show general error
} else if(data.form.has_errors){//Si hay errores de formulario
//Recorremos todos los errores
$.each(data.form, function(key, value){
if(value.error) {
$('#' + key + '-msg').html(value.message).removeClass('hidden');
} else {
$('#'+key+'-msg').html('').addClass('hidden');
}
});
} else {
// no errors on form so show info message or whatever you need
}
});
});

bootstrap : validating form fields with file attachment and redirect to same page

So i've been working on this for days and done lots of research over internet with no sucess, so i'm giving a try to understand if anyone can help me.
I've this form :
<!-- Modal form contactjobApply starts -->
<div class="modal hide fade" id="contactformjobapply" tabindex="-1" role="dialog" aria-labelledby="contactformLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><img src="images/bt_close_form.png"></button>
<h1 class="modal-title" id="contactformLabel">NOUS CONTACTER POUR :</h1>
<p class="forminformation">Sécrétaire réceptionniste français anglais</p>
</div>
<div class="modal-body">
<form class="form-horizontal" method="POST" enctype="multipart/form-data" action="formmail_apply.php" autocomplete="on">
<input type="hidden" name="Subject" value="Postulation à l'offre d'emploi">
<fieldset>
<div class="control-group">
<label class="control-label" for="textinputprenom">Prénom*</label>
<div class="controls">
<input id="textinputprenom" name="formpnom" type="text" placeholder="Votre prénom" required autofocus>
</div>
</div>
<div class="control-group">
<label class="control-label" for="textinputnom">Nom*</label>
<div class="controls">
<input id="textinputnom" name="formnom" type="text" placeholder="Votre Nom">
</div>
</div>
<div class="control-group">
<label class="control-label" for="textinputmail">Adresse e-mail*</label>
<div class="controls">
<input id="textinputmail" name="formmail" type="email" placeholder="Votre adresse e-mail" required title="Un adresse e-mail valid. Ex:. moi#gmail.com">
</div>
</div>
<div class="control-group">
<label class="control-label" for="textinputcontact">Téléphone*</label>
<div class="controls">
<input id="textinputcontact" name="formcontact" type="tel" placeholder="Votre contact par téléphone ou natel" maxlength="10" pattern="[10|0][0-9]{9}" required title="Votre nº de téléphone. Ex:. 0781231212 ou 0221231212">
</div>
</div>
<div class="control-group">
<label class="control-label" for="textinputprofession">Profession*</label>
<div class="controls">
<input id="textinputprofession" name="formprofession" type="text" placeholder="Votre profession actuelle" required>
</div>
<div class="control-group fileupload">
<label class="control-label" for="filebutton">Votre dossier*</label>
<div class="controls">
<a class="file-input-wrapper btinput">CHOISIR FICHIER
<p class="help-block2">Pas de fichier téléchargé</p>
<input id="filebutton" type="file" title="Choisir votre CV" name="filebutton" accept="text/plain,application/pdf,application/msword,application/rtf" allow="text/plain,application/pdf,application/msword,application/rtf" required placeholder="Pas de fichier téléchargé">
</a>
<p class="help-block">NB: Envoyez uniquement des fichiers au format DOC / PDF / TXT - 1Mo MAX</p>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="textarea" required>Lettre de motivation*</label>
<div class="controls">
<textarea id="textarea" name="formmessage" placeholder="Votre lettre de motivation" required></textarea>
</div>
</div>
<button type="submit" class="bt_sendform">ENVOYER</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<!-- Modal form contactjobApply ends -->
And this PHP :
<meta charset="UTF-8">
<?php
// Pear library includes
// You should have the pear lib installed
include_once('Mail.php');
include_once('Mail_Mime/mime.php');
// infos from form
$email_to = "your#mail.com";
$email_subject = "Nouveau message d'yourwebsite.com";
$upload_folder = './uploads/'; //<-- this folder must be writeable by the script
// Check for safari
function died($error) {
// your error code can go here
echo "Vos informations ne sont pas correctes<br><br><br>";
echo "Remplissez les champs suivants :<br><br>";
echo $error."<br><br>";
echo "Remplissez les champs en manque<br><br>";
die();
}
// validation expected data exists
if(!isset($_POST['formpnom']) ||
!isset($_POST['formnom']) ||
!isset($_POST['formmail']) ||
!isset($_POST['formcontact']) ||
!isset($_POST['formprofession']) ||
!isset($_POST['formmessage'])) {
died('Il semble manquer des informations');
}
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['filebutton']['name']);
//get the file extension of the file
$type_of_uploaded_file = substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file = $_FILES["filebutton"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 1024; // size in KB
$allowed_extensions = array("txt", "doc", "docx", "pdf");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size ) {
$error_message .= "\n La taille du fichier doit être plus petite";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++) {
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0) {
$allowed_ext = true;
}
}
if(!$allowed_ext) {
$error_message .= "\n Ce fichier n'est pas valable. ".
" Télécharger uniquement les fichiers suivants : ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["filebutton"]["tmp_name"];
if(is_uploaded_file($tmp_path)) {
if(!copy($tmp_path,$path_of_uploaded_file)) {
$error_message .= "\n Votre fichier n'est pas attaché, un problème est la cause";
}
}
// declare variables
$first_name = $_POST['formpnom']; // required
$last_name = $_POST['formnom']; // required
$email_from = $_POST['formmail']; // required
$telephone = $_POST['formcontact']; // required
$profession = $_POST['formprofession']; // required
$comments = $_POST['formmessage']; // required
$error_message = "";
// Check for safari
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'Un adresse e-mail valid. Ex:. moi#gmail.com<br>';
}
$phone_exp = '/^[10|0][0-9]{9}$/';
if(!preg_match($phone_exp,$telephone)) {
$error_message .= 'Votre nº de téléphone. Ex:. 0781231212 ou 0221231212<br>';
}
$string_exp = "/^[A-Za-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÕÒÓÔÖÙÚÛÜŸŒÆàáâãäåçèéêëìíîïðòóôõöùúûüýÿœæ .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= "Votre prénom n'est pas valide<br>";
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= "Votre nom n'est pas valide<br>";
}
if(!preg_match($string_exp,$profession)) {
$error_message .= "Votre profession n'est pas valide<br>";
}
if(strlen($comments) < 2) {
$error_message .= "Vous n'avez pas de message<br>";
}
if(strlen($error_message) > 0) {
died($error_message);
}
// Message before mail
$email_message .= "Prénom : ".clean_string($first_name)."\n";
$email_message .= "Nom : ".clean_string($last_name)."\n";
$email_message .= "Adresse e-mail: ".clean_string($email_from)."\n";
$email_message .= "Téléphone : ".clean_string($telephone)."\n";
$email_message .= "Profession : ".clean_string($profession)."\n";
$email_message .= "Message : ".clean_string($comments)."\n";
// create email headers
#mail($email_to, $email_subject, $email_message, $headers);
header("Location: http://bpoeta.net/pen/anj");
//send the email
$message = new Mail_mime();
$message->setTXTBody($email_message);
$message->addAttachment($path_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$email_to, "Subject"=>$email_subject,"Reply-To"=>$email_from);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($email_to, $headers, $body);
//redirect to 'thank-you page
header('Location: http://bpoeta.net/pen/anj');
?>
I've been able to make it work with input validation, and sending back to my chosen link after a sent mail, but sundenly it stop work and I can't achieve how to attach a file to a mail and send it with the mail.
I've been using bootstrap for most configurations and I would like to be able, if possible, after sending the email, to keep in the modal layer of the form, with an alert message, or send it back to the index page. and of course be able to send a file attached with the email.
I would really appreciate your help on this
got the answer :
<meta charset="UTF-8">
<?php
// files sent
if(isset($_FILES) && (bool) $_FILES) {
// define allowed extensions
$allowedExtensions = array("pdf","doc","docx","txt");
$files = array();
$maxsize = 1048576;
// loop through all the files
foreach($_FILES as $name=>$file) {
// define variables
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
// check file allow
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
$sizeu = filesize($file);
$fsize = $file['size'];
if(!in_array($ext,$allowedExtensions)) {
die("Le fichier $file_name a le format $ext qui n'est pas autorisé ou aucun fichier a été uploader.<br><br>Retournez à la page précédente");
}
if(($fsize >= $maxsize) || ($fsize == 0)) {
die("Le fichier $file_name est de $fsize Mo .<br><br>Sa taille ne doit pas dépasser 1 Mo.<br><br>Retournez à la page précédente");
}
// move the file to server
$server_file = "$path_parts[basename]";
move_uploaded_file($temp_name, $server_file);
// add file to arrays
array_push($files,$server_file);
}
// Check for safari
function died($error) {
// your error code can go here
echo "Vos informations ne sont pas correctes<br><br><br>";
echo "Remplissez les champs suivants :<br><br>";
echo $error."<br><br>";
echo "Remplissez les champs en manque<br><br>";
die();
}
// validation expected data exists
if(!isset($_POST['formnom']) ||
!isset($_POST['formmail']) ||
!isset($_POST['formsubject']) ||
!isset($_POST['formmessage'])) {
died('Il semble manquer des informations');
}
// email fields: to, from, subject, and so on
$name = $_POST['formnom']; // required
$to = "your#mail.com";
$email_fromto = "no-reply#mail.com";
$from = $_POST['formmail'];
$subject = "E-mail envoyé de yourwebsite.com";
$formsubject = $_POST['formsubject']; // required
$msg = $_POST['formmessage'];
$error_message = "";
$headers = 'From: '.$email_fromto."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();
// Check for safari
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$from)) {
$error_message .= 'Un adresse e-mail valid. Ex:. moi#gmail.com<br>';
}
$string_exp = "/^[A-Za-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÕÒÓÔÖÙÚÛÜŸŒÆàáâãäåçèéêëìíîïðòóôõöùúûüýÿœæ .'-]+$/";
if(!preg_match($string_exp,$name)) {
$error_message .= "Votre nom n'est pas valide<br>";
}
if(!preg_match($string_exp,$formsubject)) {
$error_message .= "Votre objet n'est pas valide<br>";
}
if(strlen($msg) < 2) {
$error_message .= "Vous n'avez pas de message<br>";
}
if(strlen($error_message) > 0) {
died($error_message);
}
// Message before mail
$mail_message = "Contenu de ce message\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$mail_message .= "Nom : ".clean_string($name)."\n";
$mail_message .= "Adresse e-mail: ".clean_string($from)."\n";
$mail_message .= "Objet : ".clean_string($formsubject)."\n";
$mail_message .= "Message : ".clean_string($msg)."\n";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers boundary
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
// headers plain
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Enconding: 7bit\n\n" . $mail_message . "\n\n";
$message .= "--{$mime_boundary}\n";
// loop
foreach($files as $file) {
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo '
<script type="text/javascript">
document.location = "http://yourwebsite.com"
</script>
';
} else {
echo "<p>Votre e-mail n'a pas été envoyé, un problème dans votre terminal l'empêche</p>";
}
die();
}
?>
and for the form:
<form class="form-horizontal" method="POST" action="formmail.php" autocomplete="on" enctype="multipart/form-data" accept-charset="utf-8">
Thanks a lot for the guys who helped me :)
It's hard to understand php when you're not good on math, and you only into webdesign (I mean design).
Cheers all and hope it helps others!

Categories