i'm doing a whole new login form in Wordpress.
I can register users but the wp_signon does not work at all.
Users are well registered because i can log them on the classic /wp-admin but not on my custom one.
I have an error like that :
WP_Error Object ( [errors] => Array ( [empty_password] => Array ( [0] => Erreur : le champ du mot de passe est vide. ) ) [error_data] => Array ( ) )
Where "Erreur : le champ du mot de passe est vide." means "Error : the password field is empty".
Here is my code :
<?php
/*
Template Name : Connexion
*/
$error = false;
if(!empty($_POST)) {
$userlog = array(
'user_login' => $_POST['user_login'],
'user_pass' => $_POST['user_password'],
);
$user = wp_signon($userlog);
do_action('init', $user);
if(is_wp_error($user)){
$user->get_error_message();
print_r($user);
}else{
header("Location: /");
};
}
get_header();?>
<div class="main_container">
<div class="container_form">
<h2>Se connecter</h2>
<div class="form_logo">
</div>
<?php if($error) {?>
<div class="error">
<?php echo $error ?>
</div>
<?php } ?>
<form action="<?php echo $_SERVER['REQUEST_URI'];?>" method="POST">
<label for="user_login">Identifiant</label>
<input type="text" name="user_login" id="user_login">
<label for="user_password">Mot de passe</label>
<input type="password" name="user_password" id="user_password">
<div id="button_container">
<input type="submit" name="button1" value="Se connecter" id='save'/>
</div>
</form>
</div>
</div>
<?php get_footer(); ?>
I have tried do call it on init, without init... Lot of things !
Thanks if you can help.
EDIT
The error came from the 'user_pass' it has to be 'user_password' for the wp_signon and 'user_pass' for wp_insert_user
Here is the register page on which the user is registered but not log in.
$error = false;
if(!empty($_POST)) {
if($_POST['user_password'] != $_POST['user_password2']) {
$error = "Les mots de passe ne correspondent pas";
} else {
if(!is_email($_POST['user_email'])) {
$error = "Veuillez entrer un email valide";
} else {
$user = array(
'user_login' => $_POST['user_login'],
'user_pass' => $_POST['user_password'],
'user_email' => $_POST['user_email'],
);
$user_add = wp_insert_user($user);
if (is_wp_error($user_add)) {
$error = $user_add->get_error_message();
} else {
update_field('player_league_of_legends', $_POST['user_login'], 'user_'.$user_add);
$user_login = wp_signon($user);
do_action('template_redirect', $user_login);
if(is_wp_error($user_login)){
$error = $user_login->get_error_message();
} else {
header("Location: /login");
}
}
}
}
}
This code is in index.php?
According to documentation https://developer.wordpress.org/reference/functions/wp_signon/ you must use wp_signon in function.php.
You can also use plugin https://wordpress.org/plugins/custom-login/#developers or by inspired by him
Related
I'm adding a html form to my website. I have an issue with the form validation. I'm trying to display error message when the user does not writte is email address and still submit the form.
The thing is: I'm trying to do it on the same page : so my code, as it is now, directly display the error message when the page is loaded (which is normal because the user did not enter is email address yet).
I would like this message to display on the same page (so here : on registerForm.php) only if the user clicked on the submit btn but did not enter his email address. Could someone help me please?
I put the code bellow :
registerForm.php
`
<?php
session_start();
//include a javascript file
echo "<script type='text/javascript' src='registerForm.js'></script>";
?>
<div class="divCenter">
<div class="registerform-container">
<form action="successForm.php" class="registerform-form" method="POST">
<div>
<label id="emailInput" for="email" class="registerform-form-label">Email</label>
<div>
<input type="email" class="registerform-form-control" id="email" name="email" aria-describedby="email-subscribe" placeholder="you#exemple.com">
<div id="email-help" class="registerform-form-text">L'email utilisé lors de la création de compte.</div>
</div>
</div>
<button id="button" class="registerform-btn disabled" type="submit">Send</button>
</form>
<?php
if(isset($_SESSION['statut'])){
?>
<div class="success">
<p><?php echo htmlspecialchars($_SESSION['statut']) ?></p>
</div>';
<?php
//une fois afficher il faut détruire le session
unset($_SESSION['statut']);
}
?>
</div>
</div>
successForm.php
<?php
//include CSS Style Sheet
echo "<link rel='stylesheet' type='text/css' href='registerForm.css' />";
//include a javascript file
echo "<script type='text/javascript' src='rfffff.js'></script>";
?>
<?php
if(!isset($_SESSION))
{
session_start();
}
?>
<?php
if(!isset($_POST['email']))
{
echo 'you must enter your email address'; return;
}
try
{
$db = new PDO('mysql:host=localhost;dbname=mariawebsite;charset=utf8', 'root', 'root');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$email = $_POST['email'];
// Préparation
$insertEmail = $db->prepare("INSERT INTO users_addresses(email) VALUES (:email)");
// ajouter la ligne ci-dessous pour être sûr d'afficher toutes les erreurs.
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// Exécution ! La recette est maintenant en base de données
$insertEmail->execute([
'email' => $email,
]);
$_SESSION['statut'] = "$email submited successfully";
header('Location: home.php');
?>
`
I would like this message to display on the same page (so here : on registerForm.php) only if the user clicked on the submit btn but did not enter his email address. Could someone help me please?
Try this:
On successForm.php
if(!isset($_POST['email']) || empty($_POST['email']))
{
$msg = 'you must enter your email address';
header('Location: registerForm.php?msg='.$msg); // this will redirect to register form with message
} else {
//try catch and other code here
}
On registerForm.php
After and before form starts.
Add this:
<?php if(isset($_GET['msg']) && $_GET['msg'] != "") {?>
<div class="msg_error">
<p><?php echo $_GET['msg']?></p>
</div>
<?php } ?>
I have created a simple registration/login system with PHP/SQL in MVC pattern.
It works perfectly but I noticed a little bug; when I login with user and email that they are not in my database, I can't never visualize the warning message "These user and email are not in our database". I noticed that in the http bar on the top I visualize the GET request "action="error" ONLY when then I refresh the page, and not when I immediately click the submit button for the fields control. Where is the problem?
Here my login page code:
<h2>Login</h2>
<?php
$login = new MvcTemplate();
$login -> loginUserController();
if(isset($_GET['action'])){
if($_GET['action'] == 'error'){
echo '<div class="alert alert-warning">Ops, these user and email are not in our database!</div>';
}
if($_GET['action'] == 'captchafail'){
echo '<div class="alert alert-warning">Ops, flag the Captcha!</div>';
}
}
?>
<form method="POST">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="La tua Mail" name="mail" required>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="La tua Password" name="password" required>
</div>
<div class="g-recaptcha my-5" data-sitekey="6LdJAwodAAAAALA5PrlYI9n96h5f4AmSab7SOSKC"></div>
<div class="d-grid">
<button type="submit" class="btn btn-primary" name="login">Entra</button>
</div>
</form>
Here the managing of the Login feature in the Controller:
// Gestione della funzione di Login;
public function loginUserController(){
if(isset($_POST['login'])){
// Cifratura della password mediante funzione "crypt";
$securePass = crypt($_POST['password'], '$5$zyPltHmiO9ZqMg7JHRWktNhB_GZ0jiQWvDe0c4N7$');
$dataController = array(
'mail' => $_POST['mail'],
'password' => $securePass
);
$responseDb = Data::loginUserModel($dataController, 'users');
// Controllo di ReCaptcha;
$secret = '6LdJAwodAAAAAOlQKWxeJ2LCydsRpl1M9SrsXqOZ';
$response = $_POST['g-recaptcha-response'];
$remoteIP = $_SERVER['REMOTE_ADDR'];
$verify = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteIP");
$result = json_decode($verify);
if($result -> success){
if($responseDb['email'] == $_POST['mail'] && $responseDb['pass'] == $securePass){
// Inizializzo una sessione;
session_start();
// Creo una variabile di sessione;
$_SESSION['validation'] = true;
header('location:users');
}
}elseif(empty($_POST['g-recaptcha-response'])){
header('location:captchafail');
}
else{
header('location:error');
}
}
}
And here the page links.php in the Model directory:
<?php
class Pages{
public static function showPages($links){
if( $links == 'login' ||
$links == 'users' ||
$links == 'update' ||
$links == 'logout'
){
$moduleNav = 'views/modules/'.$links.'.php';
}elseif($links == 'index'){
$moduleNav = 'views/modules/register.php';
}elseif($links == 'ok'){
$moduleNav = 'views/modules/register.php';
}elseif($links == 'error'){
$moduleNav = 'views/modules/login.php';
}elseif($links == 'captchafail'){
$moduleNav = 'views/modules/login.php';
}elseif($links == 'edit'){
$moduleNav = 'views/modules/users.php';
}else{
$moduleNav = 'views/modules/register.php';
}
return $moduleNav;
}
}
I've recently started working with PHPMailer to email my contactforms and after some puzzling, it works great. The only 'downside' is that the user gets redirected after sending an email. For example:
If one would fill in the form here, they will be redirected to another page like this one when the message sent succesfully.
My HTML for my form is the following:
<form class="form ajax-contact-form" method="post" action="php/contact.php">
<div class="alert alert-success hidden" id="contact-success">
<strong>Votre message a été envoyé avec
succès!</strong> Merci, nous contacterons vous dès que possible.
</div>
<div class="alert alert-danger hidden" id="contact-error">
<strong>Votre message n'a pas été envoyé.</strong> Vous
avez tout rempli correctement?
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="text" name="name_" id="name_" required="" class=
"form-control" placeholder="Votre nom" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="text" name="adress_" id="subject_" required=""
class="form-control" placeholder="Votre adresse" /></label>
</div>
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="number" name="zipcode_" id="zipcode_" required=
"" class="form-control" placeholder="Code postal" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="text" name="city_" id="city_" required="" class=
"form-control" placeholder="Ville ou commune" /></label>
</div>
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="tel" name="phone_" id="phone_" required=""
class="form-control" placeholder=
"Votre numéro de téléphone" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="email" name="email_" id="email_" required=""
class="form-control" placeholder="Votre adresse d'email" /></label>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label><select name="select_" id="select_" required="" class="form-control">
<option value="Invalid">
Choisi un option
</option>
<option value="CV Ketel huren">
Je veux louer une chaudière
</option>
<option value="CV Ketel kopen">
Je veux acheter une chaudière
</option>
<option value="Ik wens meer informatie">
Je veux plus d'infos
</option>
</select></label>
</div>
</div><label>
<textarea name="message_" id="message_" cols="30" rows="10" class="form-control"
placeholder="Votre message (optionel)">
</textarea></label>
<div class="mb40"></div>
<div class="clearfix">
<div class="pull-left">
<button type="submit" class="btn btn-icon btn-e">Envoi</button>
</div>
</div>
</form>
The php for my form is the following:
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
// Include PHPMailer class
include("./PHPMailer/PHPMailerAutoload.php");
// grab reCaptcha library
require_once "./reCaptcha/recaptchalib.php";
///////////////////////////////////////////////////////////////////////
// Enter your email address below.
$to_address = "info#cvketelshuren.com";
// Enter your secret key (google captcha)
$secret = "Leftout for apparent reasons";
//////////////////////////////////////////////////////////////////////
// Verify if data has been entered
if(!empty($_POST['name_']) || !empty($_POST['adress_']) || !empty($_POST['zipcode_']) || !empty($_POST['city_']) || !empty($_POST['phone_']) || !empty($_POST['email_']) || !empty($_POST['select_'])) {
$name = $_POST['name_'];
$adress = $_POST['adress_'];
$zipcode = $_POST['zipcode_'];
$city = $_POST['city_'];
$phone = $_POST['phone_'];
$email = $_POST['email_'];
$select = $_POST['select_'];
// Configure the fields list that you want to receive on the email.
$fields = array(
0 => array(
'text' => 'Naam',
'val' => $_POST['name_']
),
1 => array(
'text' => 'Adres',
'val' => $_POST['adress_']
),
2 => array(
'text' => 'Stad',
'val' => $_POST['zipcode_']." ".$_POST['city_']
),
3 => array(
'text' => 'Select',
'val' => $_POST['select_']
),
4 => array(
'text' => 'Telefoonnummer',
'val' => $_POST['phone_']
),
5 => array(
'text' => 'Mailadres',
'val' => $_POST['email_']
),
6 => array(
'text' => 'Bericht',
'val' => $_POST['message_']
)
);
$message = "Waarde collega,<br>Er werd een contactformulier ingevuld op de site cvketelshuren.com<br>Gelieve hieronder de gegevens van de klant terug te vinden.<br>";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 0; // Debug Mode
// If you don't receive the email, try to configure the parameters below:
$mail = new PHPMailer;
$mail->Host = 'mailout.one.com';
$mail->SMTPAuth = true;
$mail->Username = '***************';
$mail->Password = '************';
$mail->SMTPSecure = false;
$mail->Port = 25;
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress($to_address);
$mail->AddReplyTo($email, $name);
if (!empty($_POST['send_copy_'])) {
$mail->AddAddress($email);
}
$mail->IsHTML(true); // Set email format to HTML
$mail->CharSet = 'UTF-8';
$mail->Subject = 'Vraag via CV Ketels Huren [NL]';
$mail->Body = $message;
// Google CAPTCHA
$resp = null; // empty response
$reCaptcha = new ReCaptcha($secret); // check secret key
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
// if captcha is ok, send email
if ($resp != null && $resp->success) {
if($mail->Send()) {
$result = array ('response'=>'success');
} else {
$result = array ('response'=>'error' , 'error_message'=> $mail->ErrorInfo);
}
} else {
$result = array ('response'=>'error' , 'error_message'=>'Google ReCaptcha did not work');
}
echo json_encode($result);
} else {
$result = array ('response'=>'error' , 'error_message'=>'Data has not been entered');
echo json_encode($result);
}
?>
As you can see, an error and success message was already coded in but if redirecting is something that should happen, I want to code a custom HTML-page. Anybody that can help me set the redirect so I can start coding?
Thanks for your time!
You are not doing any redirects here. Your form tag contains action="php/contact.php", so that's where the form will submit to. If you want to go somewhere else after processing the form submission and sending a message, you can do a redirect like this:
header('Location: some_other_url/page.php');
If the form contains errors, you could redirect back to the form, passing error messages in the URL parameters.
I've created a login script where I am simply trying to match the email and password that is passed through my login form, create a session and pass through session variables and redirect the user to his account's page. This is returning bool(false)...
When registering a user I encrypt the password using the PHP password_hash method. However when I try to login my statement is returned as false and to be fair I don't know what I am doing wrong, perhaps I'm decrypting the password incorrectly, I'm not sure.
When I tried to debug it. Can't find out why it's happening.
Any help or ideas greatly welcomed and appreciated, thank you in advance.
Here is my script :
class Auth.php
public function login($db, $email, $mdp, $remember = false)
{
$user = $db->query('SELECT * FROM client WHERE (email = :email) AND confirmed_at IS NOT NULL ', ['email' => $email])->fetch(PDO::FETCH_OBJ);
/*var_dump( password_verify($mdp,($user->mdp)));*/
print_r($db->errorInfo());
if ($user && password_verify($mdp,($user->mdp)))
{ $this->connect($user);
if ($remember) {
$this->remember($db, $user->id_clt);
} //for cookie key
return $user;
} else {
return false;
}
}
login.php
<?php
require 'inc/bootstrap.php';
$auth = App::getAuth();
$db = App::getDatabase();
$auth->connectFromCookie($db);
if($auth->userLogged()){
App::redirect('account.php');
}
if(!empty($_POST) && !empty($_POST['email']) && !empty($_POST['mdp'])){
$user = $auth->login($db, $_POST['email'], $_POST['mdp'], isset($_POST['remember']));
$session = Session::getInstance();
var_dump($user);
if($user){
$session->setFlash('success' , 'Vous êtes maintenant connecté');
App::redirect('account.php');
}else{
$session->setFlash('danger', 'Identifiant ou mot de passe incorrecte');
}
}
?>
<?php require 'inc/header2.php'; ?>
<h1 align="center"> Se connecter </h1>
<form method="POST" action="" autocomplete="on">
<div class="form-group" align="center">
<label for="email">Email</label>
<input id="email" name="email" type="email" class="form-control"/>
</div>
<div class="form-group" align="center">
<label for="mdp" >Mot de passe (J'ai oublié mon mot de passe)</label>
<input id="mdp" name="mdp" type="password" class="form-control"/>
</div>
<div class="form-group" align="center">
<label>
<input type="checkbox" name="remember" value="1"> Se souvenir de moi
</label>
<button type="submit" name="forminscription" class="btn btn-primary">Se connecter</button>
</div>
<?php require 'inc/footer.php'; ?>
I'm using a form on my website to allow user to create posts on my wordpress admin.
It works fine, but I have an issue, I don't get the tags meta inside my admin.
here is my php code :
<?php
if(isset($_POST['submit'])){
$err = array();
$err['status'] = true;
$output = "";
if(empty($_POST['pseudo'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Pseudo" ne peut être vide.';
}
if(empty($_POST['mail']) || !preg_match('/[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}/',$_POST['mail'])){
$err['status'] = false;
$err['msg'][] = 'Le champs "Mail" est mal renseigné';
}
if(empty($_POST['title'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Titre" ne peut être vide.';
}
if(empty($_POST['content'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Article" ne peut être vide.';
}
if($err['status']){
$insert = array(
'post_status' => 'publish',
'post_title' => htmlentities($_POST['title']),
'post_content' => htmlentities($_POST['content']),
'post_category' => array(11),
'post_author' => 999,
);
$post_id = wp_insert_post($insert);
if($post_id != 0){
/*
TAGS
*/
if(!empty($_POST['keywords'])){
$keywords = explode(',',$_POST['keywords']);
foreach($keywords as $k=>$v){
$tag = trim(strip_tags($v));
wp_insert_term(
$tag,
'post_tag',
array(
'slug' => sanitize_title($tag)
)
);
}
}
$user_meta_values = array(
'pseudo' => htmlentities($_POST['pseudo']),
'mail' => $_POST['mail']
);
$output = add_post_meta($post_id, "user_meta", json_encode($user_meta_values)) ? 'Article inséré avec succès.' : 'Une erreur est survenue lors de l\enregistrement.' ;
}
}
else{
foreach($err['msg'] as $k=>$v)
$output .= $v . '<br />';
}
}
?>
my html form :
<form method="post" action="<?php echo site_url().'/ajouter'; ?>">
<p><label for="pseudo">Pseudo</label><input type="text" name="pseudo" id="pseudo" value="" /></p>
<p><label for="mail">Mail</label><input type="text" name="mail" id="mail" value="" /></p>
<p><label for="title">Titre</label><input type="text" name="title" id="title" value="" /></p>
<p><label for="content">Article</label><textarea name="content" id="content" rows="10" cols="15"></textarea></p>
<p><label for="keywords">Mots clés</label><input type="text" name="keywords" id="keywords" value="" /> ( séparez les mots clés par des virgules )</p>
<p><input type="submit" name="submit" value="enregistrer" /></p>
</form>
Anyone know what I'm doing wrong ? can't find out why it's not working,
thanks for your help