I´m using the Bootstrap validation from https://github.com/nghuuphuoc/bootstrapvalidator
I have the problem that the submitHandler does not work. When the form is submitted the entry is not created and the form will be loaded in the same DIV element with completely incorrect formatting.
Can someone help me or say where exactly my fault?
HTML-Code:
<!-- All page content -->
<div class="container">
<!-- Registration-Form -->
<div class="page-header">
<h3>Registrierung eines Benutzerkontos</h3>
</div>
<div class="row">
<div class="col-xs-7 col-sm-5 col-xs-offset-3">
<div class="well">
<div class="formular">
<form role="form" id="register-form" method="post" action="">
<input type="hidden" name="sum" value="<?php echo $sum ?>">
<div class="form-group">
<label class="control-label" for="username">Benutzername</label>
<div class="form-inline">
<input type="text" class="form-control" name="username" id="username">
</div>
</div>
<div class="form-group">
<label class="control-label" for="email">E-Mail Adresse</label>
<div class="form-inline">
<input type="email" class="form-control" name="email" id="email">
</div>
</div>
<div class="form-group">
<label class="control-label" for="Password">Passwort</label>
<div class="form-inline">
<input type="password" class="form-control" name="password" id="password">
</div>
</div>
<div class="form-group">
<label class="control-label" for="confirmPassword">Passwort wiederholen</label>
<div class="form-inline">
<input type="password" class="form-control" name="confirmPassword" id="confirmPassword">
</div>
</div>
<br>
<div class="form-group">
<label class="control-label" for="captcha"><strong>Sicherheitsabfrage</strong></label>
<div class="form-inline">
<input type="text" class="form-control sum" name="num1" id="num1" value="<?php echo $num1 ?>" readonly> +
<input type="text" class="form-control sum" name="num2" id="num2" value="<?php echo $num2 ?>" readonly> =
<input type="text" class="form-control captcha" name="captcha" id="captcha" maxlength="2">
<span id="spambot"></span>
</div>
</div>
<div class="form-group">
<span class="help-block"><small>Info: Diese Eingabe dient zum Schutz vor Spambot.</small></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="register">Registrieren</button>
</div>
</form>
<div id="info"></div>
</div><!--/.formular -->
</div><!--/.well -->
</div>
</div><!--/.row -->
<!-- End Registration-Form -->
</div><!--/.container -->
Java-Script:
<script src="../components/jquery-1.10.2.min.js"></script>
<script src="../components/jquery.form.js"></script>
<script src="../dist/js/bootstrap.min.js"></script>
<script src="../dist/js/bootstrapValidator.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#register-form').bootstrapValidator({
message: 'Die Eingabe ist nicht gültig',
submitHandler: function(form) {
$(form).ajaxSubmit( {
target: '#info',
success: function() {
$('#register-form').slideUp('fast');
}
});
},
fields: {
username: {
validators: {
notEmpty: {
message: 'Bitte geben Sie einen Namen ein!'
},
stringLength: {
min: 3,
max: 30,
message: 'Der Benutzername muss mindestens 3 und maximal 30 Zeichen enthalten!'
},
regexp: {
regexp: /^[a-zA-Z0-9_\.]+$/,
message: 'Der Benutzername darf nur alphabetisch, Anzahl, Punkt und Unterstrich enthalten!'
},
}
},
email: {
validators: {
notEmpty: {
message: 'Bitte geben Sie eine E-Mail Adresse ein!'
},
emailAddress: {
message: 'Das ist keine gültige E-Mail Adresse!'
}
}
},
password: {
validators: {
notEmpty: {
message: 'Bitte geben Sie ein Passwort ein!'
},
identical: {
field: 'confirmPassword',
message: 'Die Passwörter stimmen nicht überein!'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'Bitte geben Sie ein Passwort ein!'
},
identical: {
field: 'password',
message: 'Die Passwörter stimmen nicht überein!'
}
}
},
captcha: {
validators: {
notEmpty: {
message: 'Bitte geben Sie ein Ergebnis ein!'
},
callback: {
message: 'Bitte geben Sie das richtige Ergebnis ein!',
callback: function(value) {
$result = ( parseInt($('#num1').val()) + parseInt($('#num2').val()) == parseInt($('#captcha').val()) ) ;
$('#spambot').fadeOut('fast');
return $result;
}
}
}
}
}
});
});
</script>
The following PHP-Code is on top of the file
// When post "register"
if (isset($_POST['register'])) {
// Clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
// Define variables of the user input
$username = $mysqli->real_escape_string($_POST['username']);
$email = $mysqli->real_escape_string($_POST['email']);
$password = $mysqli->real_escape_string($_POST['password']);
// Email Validation
function isValidEmail($email){
return filter_var(filter_var($email, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);
}
// Check user input values for errors
$errors = array();
if(strlen($username) < 3) {
if(!$username) {
$errors[] = "Bitte geben Sie einen Benutzernamen ein!";
} else {
$errors[] = "Der Benutzername muss mindestens 3 Zeichen enthalten!";
}
}
if(!$email) {
$errors[] = "Bitte geben Sie eine E-Mail Adresse ein!";
} else if(!isValidEmail($email)) {
$errors[] = "Das ist keine gültige E-Mail Adresse!";
}
if($_POST['password'] !== $_POST['confirmPassword']) {
$errors[] = "Die Passwörter stimmen nicht überein!";
}
if($_POST['captcha'] !== $_POST['sum']) {
$errors[] = "Bitte geben Sie das richtige Ergebnis ein!";
}
if($errors) {
// Output errors and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<div class='text-danger'><strong>Es sind folgende Fehler aufgetreten:</strong><ul>". $errortext ."</ul></div>");
} else
// Create a secure password
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password.$random_salt);
// Create a new USER
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
$insert_stmt->execute();
$insert_stmt->store_result();
}
die("<p class='text-success'>Die Registrierung war erfolgreich! Sie können sich jetzt anmelden</p>");
$insert_stmt->close();
} else {
?>
<!DOCTYPE html>
<html lang="de-DE">
...
...
I hope someone can help me. I've tried already several variants, but unfortunately without any success.
I have noticed that remote validator is not functional (even in the example), so
this helped when using HTML5 (I hope):
enableByHtml5: function($field) {
return $field.attr('data-bv-remote-url');
},
Add above code into validator/remote.js
Related
I have this login, access to the database. the problem I have is that it does not insert the fields that I pass through the post.
I attach my codes to the php that sends the information to the database.
El js en los mensajes de error i el index.php
Php send the post in the BD the name is create.php.
<?php
session_start();
include_once 'conexion.php';
$objeto = new Conexion();
$conexion = $objeto->Conectar();
//recepción de datos enviados mediante POST desde ajax
$usuario = (isset($_POST['usuario'])) ? $_POST['usuario'] : '';
$email = (isset($_POST['email'])) ? $_POST['email'] : '';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$cpassword = (isset($_POST['cpassword'])) ? $_POST['cpassword'] : '';
$pass = md5($password); //encripto la clave enviada por el usuario para compararla con la clava
encriptada y almacenada en la BD
$consulta = "SELECT * FROM usuarios WHERE email = '$email'";
if(mysqli_num_rows($consulta)) {
echo 'This email already exists';
}
else {
$resultado = $conexion->prepare($consulta);
$resultado->execute();
if($resultado->rowCount() >= 1){
$data = $resultado->fetchAll(PDO::FETCH_ASSOC);
$query = "INSERT into `usuarios` (usuario, email, password)
VALUES ('$usuario', '$email', '$pass')";
}else{
$_SESSION["s_usuario"] = null;
$data=null;
}
}
print json_encode($data);
$conexion=null;
The .js contains form error messages
$('#formLogin').submit(function(e){
e.preventDefault();
var usuario = $.trim($("#usuario").val());
var password =$.trim($("#password").val());
if(usuario.length == "" || password == ""){
Swal.fire({
type:'warning',
title:'Debe ingresar un usuario y/o password',
});
return false;
}else if{
$.ajax({
url:"bd/login.php",
type:"POST",
datatype: "json",
data: {usuario:usuario, password:password},
success:function(data){
if(data == "null"){
Swal.fire({
type:'error',
title:'Usuario y/o password incorrecta',
});
}else{
Swal.fire({
type:'success',
title:'¡Conexión exitosa!',
confirmButtonColor:'#3085d6',
confirmButtonText:'Ingresar'
}).then((result) => {
if(result.value){
window.location.href = "dashboard/index.php";
}
})
}
}
});
}
else{
$.ajax({
url:"bd/registrar.php",
type:"POST",
datatype: "json",
data: {usuario:usuario, password:password},
success:function(data){
if(data == "null"){
Swal.fire({
type:'error',
title:'Error para crear el Usuario',
});
}else{
Swal.fire({
type:'success',
title:'¡Conexión exitosa!',
confirmButtonColor:'#3085d6',
confirmButtonText:'Ingresar'
}).then((result) => {
if(result.value){
window.location.href = "index.php";
}
})
}
}
});
}
});
Index.php
<html>
<head>
<title>Rem la Ràpita - Sign In</title>
<link rel="icon" type="image/png" href="../images/favicon.png" sizes="52x52"/>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="estilos.css">
<link rel="stylesheet" href="plugins/sweetalert2/sweetalert2.min.css">
<link rel="stylesheet" type="text/css" href="fuentes/iconic/css/material-design-iconic-font.min.css">
</head>
<body>
<div class="container-login">
<div class="wrap-login">
<form class="login-form validate-form" id="formLogin" action="bd/create.php" method="post">
<span class="login-form-title">Sign In</span>
<div class="wrap-input100" data-validate = "Usuario incorrecto">
<input class="input100" type="text" id="usuario" placeholder="Nom">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate = "Usuario incorrecto">
<input class="input100" type="text" id="email" placeholder="Email">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate="Password incorrecto">
<input class="input100" type="password" id="password" placeholder="Contrasenya">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate="Password incorrecto">
<input class="input100" type="password" id="cpassword" placeholder="Confirma Contrasenya">
<span class="focus-efecto"></span>
</div>
<div class="container-login-form-btn">
<div class="wrap-login-form-btn">
<div class="login-form-bgbtn"></div>
<button type="submit" name="submit" class="login-form-btn">CREAR USUARI</button>
</div>
</div>
</form>
</div>
</div>
<script src="jquery/jquery-3.3.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="popper/popper.min.js"></script>
<script src="plugins/sweetalert2/sweetalert2.all.min.js"></script>
<script src="codigo_registro.js"></script>
</body>
Attached image of the database structure.
.
Attached image of the error.
<html>
<head>
<title>Rem la Ràpita - Sign In</title>
<link rel="icon" type="image/png" href="../images/favicon.png" sizes="52x52"/>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="estilos.css">
<link rel="stylesheet" href="plugins/sweetalert2/sweetalert2.min.css">
<link rel="stylesheet" type="text/css" href="fuentes/iconic/css/material-design-iconic-font.min.css">
</head>
<body>
<?php
require('dbconnect.php');
// When form submitted, insert values into the database.
if (isset($_REQUEST['username'])) {
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con, $username);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($con, $email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con, $password);
$query = "INSERT into `usuaris` (username, password, email)
VALUES ('$username', '" . md5($password) . "', '$email')";
$select_email = mysqli_query($con, "SELECT * FROM usuaris WHERE email = '".$_POST['email']."'");
if(mysqli_num_rows($select_email)) {
echo 'This email already exists';
}
//Comprovar si les contrasenyes coincideixen
else if ($_POST["password"] === $_POST["cpassword"]) {
$result = mysqli_query($con, $query);
if ($result) {
echo "You are registered successfully.";
} else {
echo "Click here to ";
}
}
else {
echo "Les Contrasenyes no coincideixen";
}
} else {}
?>
<div class="container-login">
<div class="wrap-login">
<form class="login-form validate-form" method="post">
<span class="login-form-title">Sign In</span>
<div class="wrap-input100" data-validate = "Usuario incorrecto">
<input class="input100" type="text" name="username" placeholder="Nom" required="required">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate = "Usuario incorrecto">
<input class="input100" type="text" name="email" placeholder="Email" required="required">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate="Password incorrecto">
<input class="input100" type="password" name="password" placeholder="Contrasenya" required="required">
<span class="focus-efecto"></span>
</div>
<div class="wrap-input100" data-validate="Password incorrecto">
<input class="input100" type="password" name="cpassword" placeholder="Confirma Contrasenya" required="required">
<span class="focus-efecto"></span>
</div>
<div class="container-login-form-btn">
<div class="wrap-login-form-btn">
<div class="login-form-bgbtn"></div>
<button type="submit" class="login-form-btn">CREAR USUARI</button>
</div>
</div>
</form>
</div>
</div>
<script src="jquery/jquery-3.3.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="popper/popper.min.js"></script>
<script src="plugins/sweetalert2/sweetalert2.all.min.js"></script>
<script src="codigo_registro.js"></script>
</body>
</html>
I have modified the code and now I get the following errors.
enter image description here
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.
I'm working on a Bootstrap contact form with validation, the problem is I cannot get the PHP echo response to show on a specific DIV, after the form is sent, browser loads my contact.php file with the response. Is there any way to show the response on #success_message DIV on the same HTML? Here's my HTML:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Bootstrap 3 Contact form with Validation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css'>
<link rel='stylesheet prefetch' href='http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<form class="well form-horizontal" action="php/contacto.php" method="post" id="contact_form">
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label">Tu nombre</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="first_name" placeholder="¿Como te llamas?" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" >Tu apellido</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="last_name" placeholder="Tu apellido" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="tucorreo#mail.com" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Teléfono</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="phone" placeholder="(55)1234-5678" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Tu comentario</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea rows="4" class="form-control" name="comment" placeholder="¡Cuéntanos como podemos ayudarte!"></textarea>
</div>
</div>
</div>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">¡Listo!<i class="glyphicon glyphicon-thumbs-up"></i> Tu mensaje fue enviado, en breve nos pondremos en contacto contigo.</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<button type="submit" class="btn btn-warning" >Enviar <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.4.5/js/bootstrapvalidator.min.js'></script>
<script src="js/index.js"></script>
</body>
Here's my JS:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: '¡Queremos saber tu nombre!'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Por favor, dinos tu apellido'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Necesitamos una dirección de correo donde contactarte'
},
emailAddress: {
message: 'Tu dirección de correo no es válida'
}
}
},
phone: {
validators: {
notEmpty: {
message: 'Por favor, proporcionanos tu teléfono'
},
phone: {
country: 'MX',
message: 'Incluye un número de teléfono válido de 10 dígitos'
}
}
},
comment: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
}
}
})
.on('success.form.bv', function(e) {
$('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
$('#contact_form').data('bootstrapValidator').resetForm();
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
And my PHP:
$EmailFrom = "contacto#tuka.mx";
$EmailTo = "manuel#tuka.mx";
$Subject = "Nuevo comentario en el website";
$first_name = Trim(stripslashes($_POST['first_name']));
$last_name = Trim(stripslashes($_POST['last_name']));
$email = Trim(stripslashes($_POST['email']));
$phone = Trim(stripslashes($_POST['phone']));
$comment = Trim(stripslashes($_POST['comment']));
// prepare email body text
$Body = "";
$Body .= "Nombre: ";
$Body .= $first_name;
$Body .= "\n";
$Body .= "Apellido: ";
$Body .= $last_name;
$Body .= "\n";
$Body .= "E-mail: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Teléfono: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Comentario: ";
$Body .= $comment;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
echo "<h2>¡Gracias! Recibimos tu mensaje</h2>";
}
else{
echo "<h2>Lo sentimos, hubo un error, inténtalo nuevamente</h2>";
}
?>
I have already uploaded it here, if you want to see it working:
http://tuka.mx/beta/contacto/index.html
The first parameter for .on() method must be event.
Here
.on('success.form.bv', function(e) {
Must be:
.on('submit', function(e) {
Looks something was wrong on JS, here's a solution:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function(validator, form, submitButton) {
$('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
$('#contact_form').data('bootstrapValidator').resetForm();
var bv = form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post(form.attr('action'), form.serialize(), function(result) {
console.log(result);
}, 'json');
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: '¡Queremos saber tu nombre!'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Por favor, dinos tu apellido'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Necesitamos una dirección de correo donde contactarte'
},
emailAddress: {
message: 'Tu dirección de correo no es válida'
}
}
},
phone: {
validators: {
notEmpty: {
message: 'Por favor, proporcionanos tu teléfono'
},
phone: {
country: 'MX',
message: 'Incluye un número de teléfono válido de 10 dígitos'
}
}
},
comment: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
}
}
})
});
I wasn't sure the best way to word the title. My issue involves this function mail($to, $subject, $message, $headers); I have it running in the middle of a PHP file which takes information from a form, creates a token with stripe api and then charges that card with stripe.
Stripe still receives the data and charges the card correctly with the inclusion of the mail function, however the page doesn't show the success message like it used to, pretty much anything but the header shows after the purchase when usually the form would clear and success message would show up. It's like anything after the mail function isn't included on a succesfull form submit.
I spend most of my time in javascript, so this could completely be my lack of familiarity with PHP.
Here is the full code below.
<?php include 'head.php'; ?>
<body>
<!--header-->
<?php include 'header.php'; ?>
<!--header-->
<script type="text/javascript">
// $('input.quantity').keyup(function(){
// var value = $( this ).val();
// var bookQuantity = $( "input.bfh-number" ).text( value );
// console.log(bookQuantity);
// })
$(document).ready(function() {
$( ".quantity" )
.keyup(function() {
var value = $( this ).val();
console.log(value);
subTotal = 150 * value;
$( '.paymentTotal' ).text( '$' + subTotal );
}).keyup();
$('#payment-form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function(validator, form, submitButton) {
var chargeAmount = 3000; //amount you want to charge, in cents. 1000 = $10.00, 2000 = $20.00 ...
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val(),
name: $('.card-holder-name').val(),
address_line1: $('.address').val(),
address_city: $('.city').val(),
address_zip: $('.zip').val(),
address_state: $('.state').val(),
quantity: $('.quantity').val(),
address_country: $('.country').val()
}, chargeAmount, stripeResponseHandler);
return false; // submit from callback
},
fields: {
street: {
validators: {
notEmpty: {
message: 'The street is required and cannot be empty'
},
stringLength: {
min: 6,
max: 96,
message: 'The street must be more than 6 and less than 96 characters long'
}
}
},
city: {
validators: {
notEmpty: {
message: 'The city is required and cannot be empty'
}
}
},
zip: {
validators: {
notEmpty: {
message: 'The zip is required and cannot be empty'
},
stringLength: {
min: 3,
max: 9,
message: 'The zip must be more than 3 and less than 9 characters long'
}
}
},
email: {
validators: {
notEmpty: {
message: 'The email address is required and cannot be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
},
stringLength: {
min: 6,
max: 65,
message: 'The email must be more than 6 and less than 65 characters long'
}
}
},
cardholdername: {
validators: {
notEmpty: {
message: 'The card holder name is required and cannot be empty'
},
stringLength: {
min: 6,
max: 70,
message: 'The card holder name must be more than 6 and less than 70 characters long'
}
}
},
first_name: {
validators: {
notEmpty: {
message: 'The card holder name is required and cannot be empty'
}
}
},
cardnumber: {
selector: '#cardnumber',
validators: {
notEmpty: {
message: 'The credit card number is required and cannot be empty'
},
creditCard: {
message: 'The credit card number is invalid'
},
}
},
expMonth: {
selector: '[data-stripe="exp-month"]',
validators: {
notEmpty: {
message: 'The expiration month is required'
},
digits: {
message: 'The expiration month can contain digits only'
},
callback: {
message: 'Expired',
callback: function(value, validator) {
value = parseInt(value, 10);
var year = validator.getFieldElements('expYear').val(),
currentMonth = new Date().getMonth() + 1,
currentYear = new Date().getFullYear();
if (value < 0 || value > 12) {
return false;
}
if (year == '') {
return true;
}
year = parseInt(year, 10);
if (year > currentYear || (year == currentYear && value > currentMonth)) {
validator.updateStatus('expYear', 'VALID');
return true;
} else {
return false;
}
}
}
}
},
expYear: {
selector: '[data-stripe="exp-year"]',
validators: {
notEmpty: {
message: 'The expiration year is required'
},
digits: {
message: 'The expiration year can contain digits only'
},
callback: {
message: 'Expired',
callback: function(value, validator) {
value = parseInt(value, 10);
var month = validator.getFieldElements('expMonth').val(),
currentMonth = new Date().getMonth() + 1,
currentYear = new Date().getFullYear();
if (value < currentYear || value > currentYear + 100) {
return false;
}
if (month == '') {
return false;
}
month = parseInt(month, 10);
if (value > currentYear || (value == currentYear && month > currentMonth)) {
validator.updateStatus('expMonth', 'VALID');
return true;
} else {
return false;
}
}
}
}
},
cvv: {
selector: '#cvv',
validators: {
notEmpty: {
message: 'The cvv is required and cannot be empty'
},
cvv: {
message: 'The value is not a valid CVV',
creditCardField: 'cardnumber'
}
}
},
}
});
});
</script>
<script type="text/javascript">
// this identifies your website in the createToken call below
//Stripe.setPublishableKey('pk_live_random');
Stripe.setPublishableKey('pk_test_random');
function stripeResponseHandler(status, response) {
if (response.error) {
// re-enable the submit button
$('.submit-button').removeAttr("disabled");
// show hidden div
document.getElementById('a_x200').style.display = 'block';
// show the errors on the form
$(".payment-errors").html(response.error.message);
} else {
var form$ = $("#payment-form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
</script>
<!--content-->
<div class="global indent">
<div class="container partner-wrap">
<form action="" method="POST" id="payment-form" class="form-horizontal">
<div class="row"> <div class="col-lg-6"><img id="buyImage" src="img/book.jpg" /></div>
<div class="col-lg-6"><h2>The Economic Definition of Ore</h2><p>Price:$150</p>
<label class="control-label" for="textinput">Quantity</label>
<div class="form-group col-sm-4">
<div class="col-lg-12">
<h4>Quantity</h4>
</div>
<div class="col-lg-12">
<input type="text" name="quantity" value="1" data-buttons="false" class="quantity form-control bfh-number">
</div>
</div>
<div class="col-sm-8">
<h4 class="subTotalRight borderBottom">Total:</h4>
<h5 class="paymentTotal subTotalRight"></h5>
</div>
</div>
</div>
<div class="row row-centered">
<div class="col-md-12">
<div class="page-header">
<h2 class="gdfg">Secure Payment Form</h2>
</div>
<noscript>
<div class="bs-callout bs-callout-danger">
<h4>JavaScript is not enabled!</h4>
<p>This payment form requires your browser to have JavaScript enabled. Please activate JavaScript and reload this page. Check enable-javascript.com for more informations.</p>
</div>
</noscript>
<?php
$error = '';
$success = '';
require 'Stripe.php';
if ($_POST) {
$token = $_POST['stripeToken'];
$email = $_POST["email"];
$quantity = $_POST["quantity"];
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
// Get the values from the $_POST array:
$price = 15000;
$total = $price * $quantity;
$customertotal = $price * $quantity / 100;
//Stripe::setApiKey("sk_random");
Stripe::setApiKey("sk_random");
$error = '';
$success = '';
try {
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
"description" => $quantity . " copies of The Economic Definition of Ore -Cut-off Grades in Theory and Practice"
));
$charge = Stripe_Charge::create(array(
"amount" => $total, // amount in cents, again
"currency" => "cad",
'customer' => $customer->id,
"metadata" => array("First Name:" => $firstName, "Last Name:" => $lastName)
)
);
$success = '<div class="alert alert-success">
<strong>Success!</strong> Your payment was successful. For $' . $customertotal . ', and you have ordered ' . $quantity . ' copies </div>';
$to = $email; // note the comma
// subject
$subject = 'Economic Definition of Ore Purchase';
// message
$message = '
<html>
<head>
<title>Sumary of Purchase</title>
</head>
<body>
<table>
<tr>
<td> Hi ' . $firstName . '</td>
</tr>
<tr>
<td>
<p>Here is a summary of your recent purchase.</p>
</td>
</tr>
<tr>
<td>
<p>Your total purchase is $'.$customertotal . ' </p>
<p>The number of books you have ordered is <b>' . $quantity . '</b> </p>
</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: '. $firstName .' <' . $email . ' > ' . "\r\n";
$headers .= 'From: Comet <info#cometstrategy.com>' . "\r\n";
// $headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
}
catch (Exception $e) {
$error = '<div class="alert alert-danger">
<strong></strong> '.$e->getMessage().'
</div>';
}
}
?>
<span class="payment-success">
<?= $success ?>
<?= $error ?>
</span>
<div class="alert alert-danger" id="a_x200" style="display: none;"> <strong></strong> Please fill out all required fields. </div>
<!-- Street -->
<div class="row">
<div class="col-md-6">
<!-- Form Name -->
<legend>Billing Details</legend>
<fieldset>
<!-- Street -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">First Name</label>
<div class="col-sm-12">
<input type="text" name="firstName" placeholder="First Name" class="firstName form-control">
</div>
</div>
<!-- Street -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Last Name</label>
<div class="col-sm-12">
<input type="text" name="lastName" placeholder="Last Name" class="firstName form-control">
</div>
</div>
<!-- Street -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Street</label>
<div class="col-sm-12">
<input type="text" name="street" placeholder="Billing Address" class="address form-control">
</div>
</div>
<!-- City -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">City</label>
<div class="col-sm-12">
<input type="text" name="city" placeholder="City" class="city form-control">
</div>
</div>
<!-- State -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">State</label>
<div class="col-sm-12">
<input type="text" name="state" maxlength="65" placeholder="State" class="state form-control">
</div>
</div>
<!-- Postcal Code -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Postal Code</label>
<div class="col-sm-12">
<input type="text" name="zip" maxlength="9" placeholder="Postal Code" class="zip form-control">
</div>
</div>
<!-- Country -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Country</label>
<div class="col-sm-12">
<!--input type="text" name="country" placeholder="Country" class="country form-control"-->
<!-- <div class="country bfh-selectbox bfh-countries" name="country" placeholder="Select Country" data-flags="true" data-filter="true"> </div> -->
<select class="form-control bfh-countries" data-country="AU"></select>
<!-- <div class="bfh-selectbox bfh-countries" data-country="AU" data-flags="true"> -->
<!-- </div> -->
</div>
</div>
<!-- Email -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Email</label>
<div class="col-sm-12">
<input type="text" name="email" maxlength="65" placeholder="Email" class="email form-control">
</div>
</div>
</div>
<div class="col-md-6">
<fieldset>
<legend>Card Details</legend>
<!-- Card Holder Name -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Card Holder's Name</label>
<div class="col-sm-12">
<input type="text" name="cardholdername" maxlength="70" placeholder="Card Holder Name" class="card-holder-name form-control">
</div>
</div>
<!-- Card Number -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Card Number</label>
<div class="col-sm-12">
<input type="text" id="cardnumber" maxlength="19" placeholder="Card Number" class="card-number form-control">
</div>
</div>
<!-- Expiry-->
<div class="form-group">
<label class="col-xs-12 col-sm-12 control-label" for="textinput">Card Expiry Date</label>
<div class="col-sm-12">
<div class="form-inline">
<select name="select2" data-stripe="exp-month" class="card-expiry-month stripe-sensitive required form-control">
<option value="01" selected="selected">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<span> / </span>
<select name="select2" data-stripe="exp-year" class="card-expiry-year stripe-sensitive required form-control">
</select>
<script type="text/javascript">
var select = $(".card-expiry-year"),
year = new Date().getFullYear();
for (var i = 0; i < 12; i++) {
select.append($("<option value='"+(i + year)+"' "+(i === 0 ? "selected" : "")+">"+(i + year)+"</option>"))
}
</script>
</div>
</div>
</div>
<!-- CVV -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">CVV/CVV2</label>
<div class="col-sm-4">
<input type="text" id="cvv" placeholder="CVV" maxlength="4" class="card-cvc form-control">
</div>
</div>
<hr>
<div class="row">
<div class="col-sm-12">
<h3>Total ($USD)</h3>
</div>
<div class="col-sm-12">
<h4 class="paymentTotal"></h4>
</div>
<div class="col-sm-12">
<button class="btn btn-success" type="submit">Pay Now</button>
</div>
</div>
<!-- Important notice -->
<!-- <div class="form-group"> -->
<!-- <div class="panel panel-success"> -->
<!-- <div class="panel-heading">
<h3 class="panel-title">Important notice</h3>
</div>
<div class="panel-body">
<p>Your card will be charged 30€ after submit.</p>
<p>Your account statement will show the following booking text:
XXXXXXX </p>
</div>
</div> -->
</fieldset>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!--footer-->
<?php include 'footer.php'; ?>
<script src="js/bootstrap.min.js"></script>
<script src="js/tm-scripts.js"></script>
</body>
</html>
Is anything after the PHP block being sent to the client (if you view source, is there any HTML after <noscript> block?), or is the payment-success span just empty?
If it's the former (nothing after the PHP block), then execution is stopping after the call to mail(). If mail() is reporting some kind of error, it will not be caught by the try/catch since it is an internal function that does not throw exceptions--it relies on the older PHP error reporting mechanism. For debugging purposes, try setting error_reporting(E_ALL) and manually testing to see if mail() is returning true:
<?php // Top of the file
error_reporting(E_ALL);
include 'head.php';
?>
....
...
// In the PHP block where you call mail()
if (!mail($to, $subject, $message, $headers)) {
echo "There was a problem with mail()<br />\n";
}
Then, submit the form and see if there is a PHP error message somewhere in the output and/or the message "There was a problem with mail()'. Depending on what you find, we can go from there.
first I have to use PHP4 and SMARTY2. Yep I know it is very bad :-/ but we're unable to upgrade cause the existing systems need that environment... :#
I want to code a admin login with jquery's load and php.
There is a 3 part Login cause of the tpl system of smarty: a smarty login (with php and tpl) a forgotten php and another login php. I can only load php with jquery: not tpl and php
the first login is include in our frame.tpl
the other 2 can only used with a combination of php and html cause of the load()
I can't get the POSTs from the combinatet php's could u pls tell me how I can use it?
so here the code where i include the login.tpl:
<div id='rightcolumn'>
<div class='admin'>
<h3>ADMINISTRATOR</h3>
{include file='login.tpl'}
</div>
the login.tpl
<form method="POST">
{literal}
<script type="text/javascript">
$(document).ready(function(){
$("#load").click(function(){
$("#dynamic").load("././content/pw_lost.php");
return false;
});
});
</script>
{/literal}
<br />
<div id="dynamic">
<!--[if IE]>
Pers.Nr.:
<br /><input type="text" name="persnr" style="width:150px;" value="Pers.Nr."
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value=='')this.value=this.defaultValue;"/>
<br />
<br />
Passwort:
<br /><input type="password" name="password" style="width:150px;" value="***********"
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value=='')this.value=this.defaultValue;"/>
<br />
<br /><input type="submit" name="login" value="anmelden" />
<![endif]-->
<!--[if !IE]> -->
<fieldset id="inputs" class="field_login">
<input id="persnr" name="persnr" type="text" placeholder="Pers.Nr.">
<input id="password" name="password" type="password" placeholder="Password">
</fieldset>
<br />
<button type="submit" name="login" value="anmelden" class="myButton">Anmelden</button>
<br />
<!--<![endif]-->
<br />
<br /><div id="load">Passwort vergessen?</div>
<br />
<br />
</div>
</form>
here the forgotten.php:
and here is the problem I can't use the php block (if I don't use the first if(isset()) i get a blank page... and if i submit the whole page is reloading and didn't get any POSTs
<?php
if(isset($_POST['persnr'])) {
if (empty($_POST['persnr'])) {
$SMARTY->assign('message', 'Bitte füllen Sie alle Felder aus.');
} else {
$TMP_PERSNR = strtolower($DB->escape($_POST['persnr']));
$query = "SELECT * FROM TAB_MITARBEITER WHERE lower(NPERSNR)='$TMP_PERSNR'";
$res = $DB->query($query, TRUE);
unset($query);
if ($res) {
// also wenn es den Mitarbeiter gibt
$pool = "qwertzupasdfghkyxcvbnm";
$pool .= "23456789";
$pool .= "WERTZUPLKJHGFDSAYXCVBNM";
srand ((double)microtime()*1000000);
for($index = 0; $index < 8; $index++) {
$newpassword .= substr($pool,(rand()%(strlen ($pool))), 1);
}
$Name = "SAZ Support"; //senders name
$email = $res[0]['VCMAIL']; //senders e-mail adress
$recipient = $res[0]['VCMAIL']; //recipient
$subject = "SAZ - neues Passwort"; //subject
$header = "From: ". $Name . " <" . ">\r\n"; //optional headerfields
$mail_body = ucfirst(strtolower($res[0]['VCNAME'])) ." ". ucfirst(strtolower($res[0]['VCVORNAME'])) . ",\n\n";
$mail_body .= "gerne möchten wir Ihnen ein neues Passwort zusenden. Ihr neues Passwort lautet: $newpassword\n\n";
$mail_body .= "Sie können Ihr Passwort jederzeit unter 'Einstellungen' in der SAZ ändern.\n\n";
$mail_body .= "Wenn Sie kein neues Passwort angefordert haben und Sie glauben, dass es sich um Missbrauch der Funktion handelt, dann wenden Sie sich bitte mit dieser E-Mail an die Systemadministration.\n\n";
$mail_body .= "Mit freundlichen Grüßen\n\n";
$mail_body .= "Ihr SAZ Support\n\n";
$mail_body .= "\n";
$mail_body .= "Abfrage von folgender Maschine gestartet: {$_SERVER['REMOTE_ADDR']}\n\n";
// change pw:
$newpassword = md5($newpassword);
$query = "UPDATE TAB_MITARBEITER SET VCPASSWORT='$newpassword' WHERE lower(NPERSNR)='$TMP_PERSNR'";
$res = $DB->query($query, FALSE);
unset($query);
if (mail($recipient, $subject, $mail_body, $header) === TRUE) {
$SMARTY->assign('message', 'Passwort zugesendet.');
}
} else {
$SMARTY->assign('message', 'Fehler. Mitarbeiter nicht gefunden.');
}
}
}
?>
//HTML starts
<form method="POST">
<script type="text/javascript">
$(document).ready(function(){
$("#load").click(function(){
$("#dynamic").load("././content/2_login.php");
return false;
});
});
</script>
<div id='dynamic'>
<div id='justify'>
Wenn Sie ihr Passwort vergessen haben, oder Sie noch kein Passwort vergeben haben, dann geben Sie hier bitte Ihre Personalnummer ein und wir senden ihnen per Email umgehend ein (neues) Passwort zu (sofern ein Benutzer für Sie bereits angelegt wurde).<br /><br />
</div>
Pers.Nr:
<br />
<input type="text" name="persnr">
<br />
<br />
<input type="submit" name="lostpw" value="Passwort anfordern" />
<br />
<br />
<div id="load">Ich möchte mich einloggen.</div>
</div>
</form>