How to convert HMAC_SHA256_MAC in PHP - javascript

index.php
<form class="row g-3" action="<?php echo base_url('signin'); ?>" method="post" id="loginForm" onsubmit="return hashpass();">
<div class="col-12">
<label for="inputUsername" class="form-label">Username</label>
<input type="text" class="form-control" name="uname" id="uname" placeholder="Enter Username" required>
</div>
<div class="col-12">
<label for="inputChoosePassword" class="form-label">Password</label>
<div class="input-group" id="show_hide_password">
<input type="password" class="form-control border-end-0" name="password" required id="password" value="12345678" placeholder="Enter Password"> <i class='bx bx-hide'></i>
</div>
</div>
<div class="col-12">
<div class="d-grid">
<button type="submit" id="signin" class="btn btn-primary" onclick="hashpass();"><i class="bx bxs-lock-open"></i>Sign in</button>
</div>
</div>
</form>
<script src="<?php echo base_url(); ?>/assets/js/HmacSHA256.js"></script>
<script>
function hashpass(){
var FormName='loginForm';
document.forms[FormName]["password"].value=HMAC_SHA256_MAC("aSm0$i_20eNh3os", document.forms[FormName]["password"].value);
return true;
}
</script>
Home_Controller.php
public function signin()
{
$userModel = new UserModel();
$uname = $this->request->getPost('uname');
$password = $this->request->getPost('password');
$data = $userModel->signin($uname);
foreach($data as $key=>$value)
{
$auth_id=$value->auth_id;
$s_password=$value->password;
}
if(!empty($data))
{
if(password_verify($password, $s_password))
{
$session->set('auth_id',$auth_id);
$this->response->redirect(base_url('dashboard'));
}else{
$this->response->redirect(base_url());
}
}
else
{
$this->response->redirect(base_url());
}
}
If I get value from front end suppose value is demo enter from front end then get in controller If I print $2y$10$nxdb2IIIu0QMcXH0T0q0buKcugSUNT3muDOmelBO.fjTE5D8OrICq. So now without this script I want $2y$10$nxdb2IIIu0QMcXH0T0q0buKcugSUNT3muDOmelBO.fjTE5D8OrICq this output using PHP function.

Here is the php exmple.
<?php
echo hash_hmac('sha256', 'data', 'secret');
?>
Update the JS script
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js"></script>
<script>
function hashpass(){
var FormName='loginForm';
document.forms[FormName]["password"].value=CryptoJS.HmacSHA256(document.forms[FormName]["password"].value, "aSm0$i_20eNh3os");
return true;
}
</script>
You can check the link.
Hash HMAC

Related

Form Submit with using Jquery Ajax PHP

I know there is a lot of similar questions but I am working on this exact same problem for two days and I just gave up.
So after the form is submitted, I want to prevent the current page (updates.php) to redirect to another page (test.php).
I am trying to do this with Jquery Ajax, but in this point, I am open to any solution.
updates.php:
<form action="test.php" method="post">
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary">
</div>
</form>
test.php:
<?php
$id = $_POST['id'];
$username = $_POST['name'];
$comment = $_POST['subject'];
if(!empty($username) || !empty($comment))
{
$conn = mysqli_connect('localhost','Admin','admin123','website');
if(!$conn)
{
echo "Connection Error: " . mysqli_connect_error();
}
else
{
$INSERT = "INSERT INTO comments (id, name, comment) VALUES (?,?,?)";
$stmt = $conn -> prepare($INSERT);
$stmt -> bind_param("iss", $id, $username, $comment);
$stmt -> execute();
}
}
else { echo "All fields are required"; die();}
?>
Whatever I did I couldn't stop test.php to open.
Try this as your updates.php file instead:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function submitWithAjax(){
var name = document.getElementById("name").value;
var id = document.getElementById("id").value;
var subject = document.getElementById("subject").value;
$.post( "test.php", {name: name, id: id, subject: subject})
.done(function(data) {
alert( "Data Loaded: " + data );
});
}
</script>
</head>
<body>
<form>
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary" onclick="event.preventDefault();submitWithAjax();">
</div>
</form>
</body>
</html>

In form1 login page input email field values how to display same email id in form2 email input field without refresh the page

In form1 login page input email field values how to display same email id in form2 email input field without refresh the page while click the forgot button please any one help me.below i attched the screenshot
script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function () {
var currentActiveId;
if (sessionStorage.getItem("activeDiv")) {
currentActiveId = sessionStorage.getItem("activeDiv");
$('.form-div').removeClass("active");
$('#' + currentActiveId).addClass("active");
}
$('#btn-show-signup').click(function () {
$('.form-div').removeClass("active");
$('#signup-form').addClass("active");
currentActiveId = "signup-form";
sessionStorage.setItem('activeDiv', currentActiveId);
});
$('.btn-show-login').click(function () {
$('.form-div').removeClass("active");
$('#login-form').addClass("active");
currentActiveId = "login-form";
sessionStorage.setItem('activeDiv', currentActiveId);
});
$('#btn-show-forgot').click(function () {
// $('#forgot-email').attr('value', null);
$('.form-div').removeClass("active");
$('#forgot-form').addClass("active");
currentActiveId = "forgot-form";
sessionStorage.setItem('activeDiv', currentActiveId);
});
});
</script>
form1
<div class="form-main">
<form action="<?php echo base_url(); ?>Index.php/Login_cntrl/login" method="POST" >
<div class="field-wrap">
<label class="view-label">Email Address</label>
<input type="email" placeholder=" Email Address" name="email" id="email" class="input-control" value="<?php echo set_value('email'); ?>"/>
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="field-wrap">
<input type="password" placeholder="Password" name="password" id="password" value="<?php echo set_value('password'); ?>" />
<span class="text-danger"><?php echo form_error('password'); ?></span>
<a href="javascript:void(0)" class="btn btn-link btn-nobg" id="btn-show-forgot" >Forgot ?</a>
</div>
<div class="field-wrap">
<button type="submit" class="btn btn-submit" name="ulogin" id="ulogin" >Login</button>
</div>
<div class="field-wrap">
NEW User? Sign up
</div>
</form>
</div>
form2
<div class="form-div" id="forgot-form">
<div class="form-aside">
<h4 id="form-header">Forgot password </h4>
<p class="form-text"></p>
</div>
<div class="form-main">
<form action="<?php echo base_url(); ?>Index.php/Login_cntrl/ResetPassword" method="POST">
<div class="field-wrap">
<input type="text" name="emaill" id="emaill" placeholder="Enter your Mobile/Email Address" value="<?php echo $this->session->userdata('findemaill'); ?>" autocomplete="off" id="forgot-email"/>
</div>
<div class="field-wrap">
<input type="text" name="otp" id="otp" placeholder="Enter OTP" value="<?php echo set_value('otp'); ?>"/>
<span class="text-danger"><?php echo form_error('otp'); ?></span>
</div>
<?php echo $this->session->flashdata('passwordmissmatch'); ?>
<div class="field-wrap">
<input type="text" name="newpassword" id="newpassword" placeholder="Enter new Password" value="<?php echo set_value('newpassword'); ?>"/>
<span class="text-danger"><?php echo form_error('newpassword'); ?></span>
</div>
<div class="field-wrap">
<input type="text" name="confirmpassword" id="confirmpassword" placeholder="Re-enter new Password" value="<?php echo set_value('confirmpassword'); ?>"/>
<span class="text-danger"><?php echo form_error('confirmpassword'); ?></span>
</div>
<div class="field-wrap">
<button type="submit" name="resubmit" id="resubmit" class="btn btn-submit">submit</button>
</div>
<?php echo $this->session->flashdata('success_msg'); ?>
<div class="field-wrap">
<a href="javascript:void(0)" class="btn-show-login btn btn-link btn-nobg" >Back</a>
</div>
</form>
</div>
</div>
on form1 html
function onClickHandler(){
location.href = 'form2.html?username=' + document.getElementById('TextBoxName').value;
}
on form2 html
function parseQueryString()
{
var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
});
return queryDict;
}
function onLoadHandler(){
document.getElementById('TextBoxName').value = parseQueryString().name;
}

How to get a login form to accept a new registrant userid and password that was submitted successfully?

This is my first time asking a question on here in a long time so my formatting might be a little off.
My login form will not accept a new user registration that was submitted even though it shows the message that the form was submitted successfully. When I check the database through phpmyadmin, there is no record of the new registrant. My code is below.
index.php
<!-- Modal -->
<a href="#" class="modal" id="modal-one" aria-hidden="true">
</a>
<div class="modal-dialog">
<div class="modal-header">
×
</div>
<div class="modal-body">
<div id="content">
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
<li class="active">LOGIN </li>
<li><label>/</label></li>
<li>SIGNUP</li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="tab-pane active" id="red">
<form action="main.php" method="post" id="formID1" class="formular">
<span class="err"><?php if(isset($_GET['$message'])){ echo $_GET['$message'];} if(isset($_GET['loginerr'])){ echo $_GET['loginerr'];}if(isset($_GET['herr1'])){ echo $_GET['herr1'];} ?><br></span><br>
<div class="form-group">
<input type="text" placeholder="EMAIL ADDRESSS" name="email" class="validate[required,custom[email]] form-control" id="usr1" >
<span class="email"></span>
</div>
<div class="form-group">
<input type="password" placeholder="PASSWORD" name="password" class="validate[required] form-control" id="pwd1">
<span class="pass"></span>
</div>
<div class="form-group">
<input type="submit" id="submit1" name="login" class="submit1 btn btn-info" value="LOGIN">
</div>
<div class="modal-footer">
RESET YOUR PASSWORD
</div>
</form> </div>
<div class="tab-pane" id="orange">
<form action="main.php" method="post" id="formID2" class="formular">
<span class="err" id="a_err"><?php if(isset($_GET['$message'])){ echo $_GET['$message'];} ?><br></span><br>
<div class="form-group">
<input type="text" placeholder="EMAIL ADDRESSS" name="s_email" class="validate[required,custom[email]] form-control" id="usr2" >
<span class="email"></span>
</div>
<div class="form-group">
<input type="password" placeholder="PASSWORD" name="s_password" class="validate[required] form-control" id="spwd">
<span class="pass"></span>
</div>
<div class="form-group">
<input type="password" placeholder="CONFIRM PASSWORD" name="confirm_password" class="form-control validate[required,equals[spwd]]" id="cpwd">
<span class="rght"></span>
</div>
<div class="form-group">
<input type="submit" id="submit2" name="s_submit" class="submit2 btn btn-info" value="CREATE YOUR ACCOUNT">
</div>
<div class="modal-footer">
BY CREATING AN ACCOUNT YOU ACKNOWLEDGE THAT YOU
ACCEPT THE TERMS & CONDITIONS
</div>
</form>
</div>
</div>
</div>
</div>
</div>
sql file
CREATE TABLE IF NOT EXISTS `login` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`email` varchar(55) NOT NULL,
`password` varchar(55) NOT NULL,
`confirm_password` varchar(55) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
--
-- Dumping data for table `login`
--
INSERT INTO `login` (`id`, `email`, `password`, `confirm_password`)
validation.js
function signup_validation()
{
alert("helloooooooo");
var usr=document.getElementById("usr2").value;
alert($usr);
var pwd=document.getElementById("spwd").value;
var cpwd=document.getElementById("cpwd").value;
var atpos = usr.indexOf("#");
var dotpos = usr.lastIndexOf(".");
if(usr=="" || pwd=="" || cpwd=="" || pwd!=cpwd)
{
document.getElementById("a_err").innerHTML="Please Fill All Fields";
if(usr==""){
document.getElementById("a_err").innerHTML="Please Enter User Name";
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=usr.length) {
document.getElementById("js_error").innerHTML="Not a valid e-mail address";
}
else if(pwd==""){
document.getElementById("a_err").innerHTML="Please Enter Email";
}
else if(cpwd==""){
document.getElementById("a_err").innerHTML="Please Re-Enter password ";
}
else if(pwd!=cpwd){
document.getElementById("a_err").innerHTML="Password Do Not Match";
}
return false;
}
else{
document.getElementById("a_err").innerHTML="";
return true;
}
}
function login_validation()
{
var username=document.getElementById("usr1").value;
//alert(username);
var atpos1 = username.indexOf("#");
var dotpos1 = username.lastIndexOf(".");
var password=document.getElementById("pwd1").value;
if(username=="" || password=="")
{
document.getElementById("js_error1").innerHTML="Please Fill All Fields";
if(username==""){
document.getElementById("js_error1").innerHTML="Please Enter Your Email Id";
}
else if (atpos1<1 || dotpos1<atpos1+2 || dotpos1+2>=username.length) {
document.getElementById("js_error1").innerHTML="Not a valid e-mail address";
}
else if(password==""){
document.getElementById("js_error1").innerHTML="Please Enter Password.";
}
return false;
}
else{
document.getElementById("js_error1").innerHTML="";
return true;
}
}
main.php
<?php
include 'config.php';
session_start();
//echo "hii";
if(isset($_POST['s_submit'])){
$email=$_POST['s_email'];
//echo $email;
$pass=$_POST['s_password'];
$sql=mysqli_query($con,"INSERT INTO personal_info (`email`,`password`,`first_time_login`)VALUES('".$email."','".$pass."','0')");
header('location:index.php?$message="form successfully submitted you can login"');
}
if(isset($_POST['login'])){
$email=$_POST['email'];
$pass=$_POST['password'];
$q=mysqli_query($con,"SELECT * FROM personal_info WHERE email='".$email."' AND password='".$pass."' ");
$row_fetch=mysqli_fetch_assoc($q);
echo $row_fetch['first_name'];
$count=mysqli_num_rows($q);
if($count>0){
$id=$row_fetch['id'];
$_SESSION['id']=$id;
//$id=mysqli_insert_id($conn);
if($row_fetch['first_time_login']=="1")
{
header('location:index.php#');
}
else{
header('location:user.php');
}
}
else{
header('location:index.php?loginerr="invalid user"');
}
}
mysqli_close($con);
?>
Your <form action="" method="post" id="formID2" class="formular"> particularly the action part must have the php file on where your post code is located at (if the php code is located on a separate file)
Example:
<form action="main.php" method="post" id="formID2" class="formular">
or
<form action="your_file_name.php" method="post" id="formID2" class="formular">

editing multiple users using modal form (javascript, html)

Hi guys the issue I have is within my users admin page, I have displayed all the admin users within a table each assigned a delete and edit button.
When I click on edit the given users details appear in a modal form. Within the edit details there is a password and confirm password box, when I click on the edit details for the first user, the validation for confirm password appears as "passwords don't match" however when I click on the second user the confirm password does not validate.
Below is the source code I am having issues with any help will be much appreciated:
<a rel="tooltip" title="Edit" id="e<?php echo $id; ?>" href="#edit<?php echo $id; ?>" data-toggle="modal" class="btn btn-success"></i>Edit</a>
<div id="edit<?php echo $id;?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-body">
<div class="alert alert-info"><strong>Edit User</strong></div>
<form class="form-horizontal" method="post">
<div class="control-group">
<label class="control-label" for="inputEmail">Firstname</label>
<div class="controls">
<input type="text" id="inputEmail" name="firstname" value="<?php echo $row['firstname']; ?>" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Lastname</label>
<div class="controls">
<input type="text" id="inputEmail" name="lastname" value="<?php echo $row['lastname']; ?>" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Mobile Number</label>
<div class="controls">
<input type="text" id="inputEmail" name="mobilenumber" value="<?php echo $row['mobilenumber']; ?>" required>
</div>
</div>
<input type="hidden" id="inputEmail" name="id" value="<?php echo $row['admin_id']; ?>" required>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input type="text" name="password" id="password" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Confirm Password</label>
<div class="controls">
<input type="text" name="confirmpassword" id="confirmpassword" required>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="edit" type="submit" class="btn btn-success"> Update</button>
</div>
</div>
<script type="text/javascript">
window.onload = function () {
document.getElementById("password").onchange = validatePassword;
document.getElementById("confirmpassword").onchange = validatePassword;
}
function validatePassword(){
var confirmpassword=document.getElementById("confirmpassword").value;
var password=document.getElementById("password").value;
if(password!=confirmpassword)
document.getElementById("confirmpassword").setCustomValidity("Passwords Don't Match");
else
document.getElementById("confirmpassword").setCustomValidity('');
//empty string means no validation error
}
</script>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true"> Close</button>
</div>
</div>
<?php
if (isset($_POST['edit'])){
$admin_id=$_POST['id'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$mobilenumber=$_POST['mobilenumber'];
$password= sha1 ($_POST['password']);
mysql_query("update admin set firstname = '$firstname', lastname = '$lastname', mobilenumber = '$mobilenumber', password = '$password' where admin_id='$admin_id'")or die(mysql_error()); ?>
<script>
window.location="adminusers.php";
</script>
<?php
}
}
?>
Validation issue
Validation issue 2

A singular behavior about a Registration form in PHP

I have a registration form in my (project of) website of the following form: (i used bootstrap framework):
<div id="main-box" class="container">
<div class="row-fluid">
<div id="signup">
<div id="float"></div>
<div id="center_signup">
<h3>Registrazione Studente</h3>
<?php if (isset($registerError)): ?>
<p><?php htmlout($registerError); ?></p>
<?php endif; ?>
<form action="" method="post" class="form-horizontal">
<div class="form-group">
<label for="nome" class="col-sm-2 control-label">Nome: </label>
<div class="col-sm-6">
<input type="text" name="nome" id="nome" class="form-control">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email: </label>
<div class="col-sm-6">
<input type="text" name="email" id="email" class="form-control">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-6">
<input type="password" name="password" id="password" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Now the data of the form are managed from a index.php controller file, which do this (the register.html.php file is the template file in which there is the code above):
if (isset($_GET['register']))
{
include 'register.html.php';
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['registerError'] = 'fill in both fields';
exit();
}
$password = md5($_POST['password'] . 'figarodb');
if (databaseContainsUser($_POST['email'], $password))
{
$GLOBALS['registerError'] = 'Student already registered.';
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/figaro/includes/db.inc.php';
// Puts the student in the relevant table
try
{
$sql = 'INSERT INTO studente SET
nome = :nome,
email = :email,
password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':nome', $_POST['nome']);
$s->bindValue(':email', $_POST['email']);
$s->bindValue(':password', $password);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Errore in student registration.';
include $_SERVER['DOCUMENT_ROOT'] . '/figaro/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
This header might redirect at the home page, but it doesn't do it!
If instead of the page with bootstrap and javascript code, i modify the registration page in this way:
<body>
<h1>Registration</h1>
<form action="" method="post">
<?php if (isset($registerError)): ?>
<p><?php echo $registerError; ?></p>
<?php endif; ?>
<div>
<label for="name">Nome completo: <input type="text" name="nome"
id="nome"></label>
</div>
<div>
<label for="email">Email: <input type="text" name="email"
id="email"></label>
</div>
<div>
<label for="password">Password: <input type="password"
name="password" id="password"></label>
</div>
<div>
<input type="submit" value="Invio">
</div>
</form>
</body>
now the controller redirect at the home page correctly!
I can not explain this behavior, any help will be greatly appreciated!Thanks!
In your php file there is written :
header('Location: .');
Maybe your web application is redirected on index.html by default because it's the default root.

Categories

Resources