How Can I show array content inside the body of html - php

This is my custom user registration form WordPress site, actually, this is my first custom development, and here all the data passes the DB my problem is I need to show my error message inside the HTML code. how can I do it? can anyone help me to solve this problem? now my error messages show like this (Array ( [username_empty] => Needed Username [email_valid] => Email has no valid value [texnumber_empty] => Needed Tax Number )) but I need only show error message only Ex: this one ( [username_empty] => Needed Username) I need to show "Needed Username"
Like this.
if (is_user_logged_in()) {
// echo '<script>alert("Welcome, registered user!")</script>';
echo '<script type="text/javascript">';
echo 'alert("Welcome, registered user!");';
echo 'window.location.href = "Url";';
echo '</script>';
} else {
// echo 'Welcome, visitor!';
global $wpdb;
if ($_POST) {
$username = $wpdb->escape($_POST['user_login']);
$email = $wpdb->escape($_POST['user_email']);
$taxnumber = $wpdb->escape($_POST['tax_number']);
$password = $wpdb->escape($_POST['user_pass']);
$ConfPassword = $wpdb->escape($_POST['user_confirm_password']);
$error = array();
if (strpos($username, ' ') !== FALSE) {
$error['username_space'] = "Username has Space";
}
if (empty($username)) {
$error['username_empty'] = "Needed Username";
}
if (username_exists($username)) {
$error['username_exists'] = "Username already exists";
}
if (!is_email($email)) {
$error['email_valid'] = "Email has no valid value";
}
if (email_exists($email)) {
$error['email_existence'] = "Email already exists";
}
if (empty($taxnumber)) {
$error['texnumber_empty'] = "Needed Tax Number";
}
if (strcmp($password, $ConfPassword) !== 0) {
$error['password'] = "Password didn't match";
}
if (count($error) == 0) {
$user_id = wp_create_user($username, $password, $email);
$userinfo = array(
'ID' => $user_id,
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_user_meta($user_id, 'tax_number', $taxnumber);
echo '<script type="text/javascript">';
echo 'alert("User Created Successfully");';
echo 'window.location.href = "url";';
echo '</script>';
exit();
} else {
print_r($error);
}
}
?>
<section id="wholesale-custom-register-form">
<div class="container wholesale-custom-register-form">
<div class="register-form">
<div class="register-form-title">
<h1>Wholesale Register Form</h1>
</div>
<div class="wholesale-register">
<form class="register-fm" method="POST">
<div class="form-group">
<label>User Name</label>
<input class="form-control" type="text" name="user_login" id="user_login" placeholder="Username" />
<?php foreach ($error as $error) {
echo $error . "<br>";
} ?>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="user_email" id="user_email" placeholder="Email" />
</div>
<div class="form-group">
<label>Tax Number</label>
<input class="form-control" type="text" name="tax_number" id="tax_number" placeholder="Tax Number" />
</div>
<div class="form-group">
<label>Enter Password</label>
<input class="form-control" type="password" name="user_pass" id="user_pass" placeholder="Password" />
</div>
<div class="form-group">
<label>Enter Cofirm Password</label>
<input class="form-control" type="password" name="user_confirm_password" id="user_confirm_password" placeholder="Cofirm Password" />
</div>
<div class="form-group">
<button class="custom-register-btn" type="submit" name="btnsubmit">Log In</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
};
This is my code I will try many times but I can't get the error messages inside the HTML body.

You want to make an AJAX call to register a user then use a callback function to check for success. If a field is invalid you also check it with javascript.
So you would need to refactor your code, seperate it into frontend/backend code and connect it via AJAX.
Write your PHP code as "add_action_hook" and register function
Onclick validate fields and inputs
Call the hook via AJAX (url: "/wp-admin/admin-ajax.php")
Return result
These are just very abstract steps, you'll need to gather some intel for yourself. You could take a look at this: https://awhitepixel.com/blog/wordpress-use-ajax/ and https://docs.wpvip.com/technical-references/security/validating-sanitizing-and-escaping/

I would do something like this
if (is_user_logged_in()) {
// echo '<script>alert("Welcome, registered user!")</script>';
echo '<script type="text/javascript">';
echo 'alert("Welcome, registered user!");';
echo 'window.location.href = "Url";';
echo '</script>';
} else {
// echo 'Welcome, visitor!';
global $wpdb;
if ($_POST) {
$username = $wpdb->escape($_POST['user_login']);
$email = $wpdb->escape($_POST['user_email']);
$taxnumber = $wpdb->escape($_POST['tax_number']);
$password = $wpdb->escape($_POST['user_pass']);
$ConfPassword = $wpdb->escape($_POST['user_confirm_password']);
if (strpos($username, ' ') !== FALSE) {
$errorMsg[] = "Username has Space";
}
if (empty($username)) {
$errorMsg[] = "Needed Username";
}
if (username_exists($username)) {
$errorMsg[] = "Username already exists";
}
if (!is_email($email)) {
$errorMsg[] = "Email has no valid value";
}
if (email_exists($email)) {
$errorMsg[] = "Email already exists";
}
if (empty($taxnumber)) {
$errorMsg[] = "Needed Tax Number";
}
if (strcmp($password, $ConfPassword) !== 0) {
$errorMsg[] = "Password didn't match";
}
if (count($errorMsg) == 0) {
$user_id = wp_create_user($username, $password, $email);
$userinfo = array(
'ID' => $user_id,
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_user_meta($user_id, 'tax_number', $taxnumber);
echo '<script type="text/javascript">';
echo 'alert("User Created Successfully");';
echo 'window.location.href = "url";';
echo '</script>';
exit();
} else {
print_r($errorMsg);
}
}
?>
<section id="wholesale-custom-register-form">
<div class="container wholesale-custom-register-form">
<div class="register-form">
<div class="register-form-title">
<h1>Wholesale Register Form</h1>
</div>
<div class="wholesale-register">
<form class="register-fm" method="POST">
<div class="form-group">
<label>User Name</label>
<input class="form-control" type="text" name="user_login" id="user_login" placeholder="Username" />
<?php foreach ($errorMsg as $error) {
?>
<div>
<strong><?= $error; ?> </strong>
</div>
<?php
} ?>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="user_email" id="user_email" placeholder="Email" />
</div>
<div class="form-group">
<label>Tax Number</label>
<input class="form-control" type="text" name="tax_number" id="tax_number" placeholder="Tax Number" />
</div>
<div class="form-group">
<label>Enter Password</label>
<input class="form-control" type="password" name="user_pass" id="user_pass" placeholder="Password" />
</div>
<div class="form-group">
<label>Enter Cofirm Password</label>
<input class="form-control" type="password" name="user_confirm_password" id="user_confirm_password" placeholder="Cofirm Password" />
</div>
<div class="form-group">
<button class="custom-register-btn" type="submit" name="btnsubmit">Log In</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
};

Related

Error message not shown when trying to login to an invalid username

When I tried logging in to an invalid username, I got no error message. Instead it redirected to the same login page.
Here is the controller:
function cekuser()
{
$username = strip_tags(stripslashes($this->input->post('username', TRUE)));
$password = strip_tags(stripslashes($this->input->post('password', TRUE)));
$u = $username;
$p = md5($password);
$cadmin = $this->Auth_model->check_login($u, $p);
if (!$cadmin) {
redirect('administrator/gagallogin');
} else {
if ($cadmin['level'] == '1') {
$this->session->set_userdata('masuk', true);
$this->session->set_userdata('user', $u);
$this->session->set_userdata('akses', '1');
$idadmin = $cadmin['id'];
$user_nama = $cadmin['nama'];
$this->session->set_userdata('idadmin', $idadmin);
$this->session->set_userdata('nama', $user_nama);
}
}
if ($this->session->userdata('masuk') == true) {
redirect('administrator/berhasillogin');
} else {
redirect('administrator/gagallogin');
}
}
function berhasillogin()
{
redirect('dashboard');
}
function gagallogin()
{
$url = base_url('administrator');
echo $this->session->set_flashdata('msg', 'Username Atau Password Salah');
redirect($url);
}
and here is for the login views:
<form class="form-signin" action="<?php echo base_url() . 'administrator/cekuser' ?>" method="post">
<label for="inputEmail" class="sr-only">NIP</label>
<input class="form-control" type="text" name="username" placeholder="Username" required>
<br />
<label for="inputPassword" class="sr-only">Password</label>
<input class="form-control" type="password" name="password" placeholder="Password" style="margin-bottom:1px;" required>
<br />
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
Is there any solution? Thank you.
You don't echo the flash data, you just set it.
function gagallogin()
{
$url = base_url('administrator');
$this->session->set_flashdata('msg', 'Username Atau Password Salah');
redirect($url);
}
In the form, you set the flash message with PHP. Change your form to a PHP file and do something like this:
<?php if ($this->session->flashdata('msg') { ?>
<p class="text-danger">Error: <?php echo $this->session->flashdata('msg'); ?></p>
<?php } ?>
<form class="form-signin" action="<?php echo base_url() . 'administrator/cekuser' ?>" method="post">

Cannot display alert once the user login inputs incorrect credentials PHP PDO

index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>

Instead of a div being shown, the form is sent

The following should output a div if the data is not entered in the input fields or if the passwords don't match, but it does not happen:
<?php
$data = $_POST;
if(isset($data['action_signup'])){
$errors = array();
if(trim($data['email'])==''){
$errors[] = 'Введите email';
}
if(trim($data['login'])==''){
$errors[] = 'Введите имя пользователя';
}
if($data['password']==''){
$errors[] = 'Введите пароль';
}
if($data['enterpassword'] != $data['password']){
$errors[] = 'Пароль введен не верно';
}
if(empty($errors)){
//Все заебись
}else{
echo '<div class="error_div">'.array_shift($errors).'</div>';
}
}
?>
Form:
<form action="/Register.php" method="post">
<div class="containerForTextRegister"><a class="register">РЕГИСТРАЦИЯ</a>
</div>
<div class="container_inputs">
<input class="register_input_email" name="email" placeholder="e-mail" required type="email" maxlength="40" value="<?php echo #$data['email'];?>">
<input class="register_input_login" name="login" placeholder="login" required maxlength="12" value="<?php echo #$data['login'];?>">
<input class="register_input_password" name="password" placeholder="password" required pattern="^[a-zA-Z]+$" maxlength="30">
<input class="register_input_enterpassword" name="enterpassword" placeholder="enter password" required pattern="^[a-zA-Z]+$" maxlength="30">
<div class="buttons_container">
<button class="button_entrance"><a class="text_button_entrance">войти</a></button>
<button class="button_register"><a class="text_button_register" name="action_signup">регистрация</a></button>
</div>
</div>
</form>
A div window should appear, but the data is just sent and that’s it. Help, I will be very grateful
You have to change your html code <button class="button_register"><a class="text_button_register" name="action_signup">регистрация</a></button> to
Or
if(isset($data['action_signup'])) to if(isset($data['email']))
like
<?php
$data = $_POST;
if(isset($data['email'])){
$errors = array();
if(trim($data['email'])==''){
$errors[] = 'Введите email';
}
if(trim($data['login'])==''){
$errors[] = 'Введите имя пользователя';
}
if($data['password']==''){
$errors[] = 'Введите пароль';
}
if($data['enterpassword'] != $data['password']){
$errors[] = 'Пароль введен не верно';
}
if(empty($errors)){
//Все заебись
}else{
echo '<div class="error_div">'.array_shift($errors).'</div>';
}
}
?>

PHP-validation error message doesn’t go after the user refresh the page

Problem is: If I write the wrong input for example: under username the number of character must be from 2-25 and I write only one character then error is shown and after I refresh the page the error doesn't go. How to remove the validation error after I refresh the page. There are three files: register.php Account.php and register-handlers.php
register.php
<!DOCTYPE html>
<?php
include("includes/classes/Accounts.php");
$account1 = new Accounts();
include("includes/handlers/register-Handlers.php");
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Register your free account</title>
</head>
<body>
<div id="inputContainer">
<form id="loginForm" action="login.php" method="POST">
<h2> Login to your account</h2>
<p>
<label for="loginusername">Username</label>
<input type="text" id="loginusername" placeholder="eg:shaahil" required>
</p>
<p>
<label for="loginpassword">password</label>
<input type="password" id="loginpassword" placeholder="type your password" required>
</p>
<button type="submit" name="LOGINB">Login</button>
</form>
</div>
<form id="registerpage" action="register.php" method="POST">
<h2>Create your free account</h2>
<p>
<?php echo $account1 -> getError("the character must be between 5 to 25 "); ?>
<label for="username1">Username</label>
<input type="text" name="username1" id="username1" placeholder="username" required>
</p>
<p>
<?php echo $account1->getError("your first name must have character between 2 to 25 ");?>
<label for="firstname">First name</label>
<input name="firstname" type="text" id="firstname" placeholder="eg:shaahil" required>
</p>
<p>
<?php echo $account1->getError("your last name must have character between 2 to 25 ");?>
<label for="lastname">Last name</label>
<input name="lastname" type="text" id="lastname" placeholder="eg:abraham" required>
</p>
<p>
<?php echo $account1->getError("invalid password ");?>
<?php echo $account1->getError("abc");?>
<?php echo $account1->getError("the password must be between 5 to 25 characters");?>
<label for="password">Password</label>
<input name="password" type="password" id="password" placeholder="enter your password" required>
</p>
<p>
<label for="password1">Confirm password</label>
<input name="password1" id="password1" type="password" placeholder="Confirm your password" required>
</p>
<p>
<?php echo $account1->getError("Email is invalid");?>
<label for="email1">Email</label>
<input name="email1" type="email" id="email1" placeholder="enter your email" required>
</p>
<button type="submit" name="Registerbutton">Register</button>
</form>
</body>
</html>
register-handlers.php
<?php
function sanitizeFormUsername($inputText){
$inputText = strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
$inputText=ucfirst(strtolower($inputText));
return $inputText;
}
function sanitizeFormString($inputText){
$inputText = strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
$inputText=ucfirst(strtolower($inputText));
return $inputText;
}
function sanitizeFormEmail($inputText){
$inputText=strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
return $inputText;
}
function sanitizeFormPassword($inputText){
$inputText=strip_tags($inputText);
return $inputText;
}
if(isset($_POST['Registerbutton'])){
$username1 = sanitizeFormUsername($_POST['username1']);
$firstname = sanitizeFormUsername($_POST['firstname']);
$lastname = sanitizeFormUsername($_POST['lastname']);
$email1 = sanitizeFormEmail($_POST['email1']);
$password= sanitizeFormPassword($_POST['password']);
$password1= sanitizeFormPassword($_POST['password1']);
$wasSuccessful = $account1->register($username1, $firstname, $lastname, $email1, $password, $password1);
if($wasSuccessful==true){
header("Location: index.php");
}
?>
Accounts.php
<?php
class Accounts{
private $errorArray;
public function __construct(){
$this->errorArray = array();
}
public function register($un1, $fn1, $ln, $em, $ps, $ps1)
{
$this->validateusername($un1);
$this->validatefirstname($fn1);
$this->validatelastname($ln);
$this->validateemail1($em);
$this->validatepasswords($ps,$ps1);
if(empty($this->errorArray) == true){
return true;
}
else {
return false;
}
}
public function getError($error) {
if(!in_array($error, $this->errorArray)) {
$error = "";
}
return " <span class='errorMessage'>$error</span> ";
}
private function validateusername($un){
if(strlen($un) > 25 || strlen($un) < 5 ){
array_push($this->errorArray , "the character must be between 5 to 25 ");
return;
}
}
private function validatefirstname($fn){
if(strlen($fn) > 25 || strlen($fn) < 2){
array_push($this->errorArray , "your first name must have character between 2 to 25 ");
return;
}
}
private function validatelastname($ln){
if(strlen($ln)>25 || strlen($ln)<2){
array_push($this ->errorArray , "your last name must have character between 2 to 25 ");
return;
}
}
private function validatepasswords($ps,$ps1){
if($ps!=$ps1){
array_push($this ->errorArray , "invalid password ");
return;
}
if(preg_match('/[^A-Za-z0-9]/', $ps)) {
array_push($this->errorArray, "abc");
return;
}
if(strlen($ps)>25 || strlen($ps)<5){
array_push($this->errorArray , "the password must be between 5 to 25 characters");
return;
}
}
private function validateemail1($em1){
if(!filter_var($em1,FILTER_VALIDATE_EMAIL)){
array_push($this ->errorArray , "Email is invalid");
return;
}
}
}
?>
This is not an answer, but rather a suggestion.
You are probably better keying your errors array with something like the field name to make error message retrieval easier.
I've adapted one of your validation methods so that it's possible to add multiple errors per field:
<?php
class AccountValidator
{
public $errors;
public function validateLastname($ln)
{
if(strlen($ln)>25 || strlen($ln)<2){
$this ->errors['lastname'][] =
"Your last name must have between 2 and 25 characters.";
return false;
}
}
}
$firstname = 'X';
$lastname = 'O';
$validator = new AccountValidator;
if($validator->validateLastname($lastname) === false)
{
echo
'<ul><li>',
implode('</li><li>', $validator->errors['lastname']),
'</li></ul>';
}
Output:
<ul><li>Your last name must have between 2 and 25 characters.</li></ul>

Forgot password reset not displaying correct email address and not updating password if any error made by user during for submission

I am currently working on PHP forgot password reset, which partially doing the job but seeking some assistance to improve it further.
1st issue: It is not displaying the correct email address on the
submission form. It updates the password correctly but doesn't
display correct email address.
2nd issue: Also if the user makes an error while submitting the form on reloading the page doesn't update the password hence the user has to go back to his email to click back on the link.
<?php
include('../config/connection.php');
if(isset($_POST['submit'])){
$password = mysqli_real_escape_string($dbc,$_POST['password']);
$Rpassword = mysqli_real_escape_string($dbc,$_POST['Rpassword']);
$acode=$_POST['encrypt'];
$passmd = md5(SHA1($password));
if (empty($password) OR empty($Rpassword)) {
$error = 'One or either field is missing';
} if ($password != $Rpassword) {
$error = 'Passwords don\'t match';
} if(strlen($password)<6 OR strlen($Rpassword)>20) {
$error = 'Password must be between 6 to 20 characters';
}
else {
$query = mysqli_query($dbc,"select * from users where passreset='$acode'") or die(mysqli_error($dbc));
if (mysqli_num_rows ($query)==1)
{
$query3 = mysqli_query($dbc,"UPDATE users SET password='$passmd',passreset=0 WHERE passreset='$acode'")
or die(mysqli_error($dbc));
$sent = 'Password has been Changed successfully, Please sign in for loging in.';
}
else
{
$error = 'Please click back on the Forgot password link to reset your password ';
}
}
}
?>
<body>
<?php if(!isset($_POST['submit']) OR $error != '' OR isset($error)) { ?>
<?php if(isset($error) AND $error !='')
{
echo '<p style="color:#c43235">'.$error.'</p>';
}
?>
<form action="reset.php" method="post" role="form">
<div class="form-group">
<label for="password">Email</label>
<input type="text" class="form-control" id="email" name="email" value="
<?php
$acode=$_POST['encrypt'];
$query5 = mysqli_query($dbc,"SELECT * FROM users where passreset='$acode'") or die(mysqli_error($dbc));
$list = mysqli_fetch_array($query5); /* Error-----*/
$val = $list['email'];
echo $val;?>" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" >
</div>
<div class="form-group">
<label for="password">Re-enter Password</label>
<input type="password" class="form-control" id="password" name="Rpassword" placeholder="Password" >
</div>
<input type="hidden" class="form-control" name="encrypt" value="<?php echo $_GET['encrypt'];?>" >
<button class="btn btn-success" type="submit" name="submit" />Submit</button>
</form>

Categories