I have a simple login form in which I have passed the values through AJAX call. The problem is when I enter wrong email or password for first time, It displays me the error message. 2nd time if I enter something wrong it does not show the error. Where am I doing wrong any suggestions/help please.
Form
<?php
if (isset($_SESSION['login_email']) && !empty($_SESSION['login_email'])) {
//header('Location:profile.php');
?>
<script> location.replace("profile.php"); </script>
<?php
} else {
?>
<div class="login_form">
<h1 class="login_heading">Login</h1>
<div class="alert-error"></div>
<div class="alert-success"></div>
<div class="login">
<form method="post" action="">
<label >Email</label>
<input class="inputs_login" type="email" name="email" id="email" placeholder="email" >
<label>Password</label>
<input class="inputs_login" type="password" name="password" id="password" placeholder="password"><br>
<input type="button" name="login_submit" id="login_submit" value="login">
</form>
</div>
</div>
<?php
}
?>
Ajax
<script>
$(document).ready(function() {
$('#login_submit').click(function(e){
//e.preventDefault();
var email = $("#email").val(),
password = $("#password").val();
var proceed = true;
if(proceed){
post_data= { 'Email': email, 'Password': password};
$.post('login_index.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output=$('.alert-error').html(response.text);
}else{
location.href="profile.php";
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
php
<?php
include "db/db.php";
session_start();
if ($_POST) {
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if (isset($_POST['Email']) && isset($_POST['Password'])) {
$email = filter_var($_POST["Email"], FILTER_SANITIZE_STRING);
$pwd = filter_var($_POST["Password"], FILTER_SANITIZE_STRING);
$query = mysqli_query($con, "select * from customers where email='$email' and password='$pwd'");
$count = mysqli_num_rows($query);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
if ($row) {
$_SESSION['login_email'] = $row['email'];
$output = json_encode(array(
'type' => 'message',
'text' => 'Hi ' . $email . ' You are successfully login'
));
die($output);
} else {
$output = json_encode(array(
'type' => 'error',
'text' => 'Could not Login! Please check your email/password OR REGISTER FREE ACCOUNT .'
));
die($output);
}
}
}
?>
Related
I have a form for password recovery via email. I send input to PHP to do the following:
Validate {three different validation messages)
If passed, Process
Once the response is received, in AJAX, although is not valid, it is considered successful because it has been processed in php.
I need to differentiate between every response so I can display appropriate alert messages
if field input is empty, I want to show it in alert-info message box
if field input is noa t valid email, I want to show it in alert-warning message box
if field input is not found the in server, I want to show it in alert-danger message box
if successful, I want to show it in alert-success
$(function() {
// Get FORM ID ///////////////////////////////////////////
var form = $('#RecoveryForm');
// Get MESSAGE DIV ID ///////////////////////////////////////////
var formMessages = $('#formresults');
$(form).submit(function(e) {
$( "#submit" ).prop( "disabled", false );
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
// Get FORM ID ///////////////////////////////////////////
document.getElementById("RecoveryForm").reset();
//$('#reset-button').click();
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
$("#submit").removeAttr("disabled");
});
});
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="formresults"></div>
<form id="RecoveryForm" method="post" action="exa.php">
<table align="center">
<tr><td><div class="input-append"><input type="text" name="email" id="email" class="input-xlarge" placeholder="Email" maxlength="100" /><span class="add-on"><li class="icon-envelope"></li></span></div></td></tr>
</table>
<input type="hidden" name="token" value="<?=Token::generate();?>" />
<center><input type="submit" id="submit" name="Forget" class="btn btn-primary" value="Submit" /></center>
</form>
<script src="ajax/jquery-2.1.0.min.js"></script>
<script src="ajax/app.js"></script>
<!---------------------------------------------------------------->
<?php include 'footer.php'; ?>
</body>
</html>
PHP Code >>
<?php
header('Content-type: application/json');
require 'Access.php'; // Get Access
//response array with status code and message
$response_array = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["email"];
if ( empty($email) ) {
$response_array['status'] = 'info';
$response_array['message'] = 'No Input';
echo json_encode($response_array);
exit;
}
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
$response_array['status'] = 'warning';
$response_array['message'] = 'Not Valid Email';
echo json_encode($response_array);
exit;
}
if (#mysql_num_rows(mysql_query("SELECT `id` FROM `accounts` WHERE `email`='$email'")) < 1) {
$response_array['status'] = 'danger';
$response_array['message'] = 'Account Not Found';
echo json_encode($response_array);
exit;
}
$row_user = #mysql_fetch_array(mysql_query("SELECT * FROM `accounts` WHERE `email`='$email'"));
$password = $row_user['pass'];
$to = $row_user['email'];
$subject = "Your Recovered Password";
$message = "Please use this password to login: " . $password;
$headers = "From : XXX#hotmail.com";
// Send the email.
if (mail($to, $subject, $message, $headers)) {
$response_array['status'] = 'Success';
$response_array['message'] = 'Email Sent';
echo json_encode($response_array);
} else {
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
}
} else {
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
}
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
?>
First of all we start validation from the html of cause this can be hampered and manipulated by the user but still a good way to start.
first we add the required attribute to your input fields in html and change the input types to match the data types your expecting eg: input type="email" hiding an input does not prevent it form being tampered with, best to add the Readonly attribute also.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="formresults"></div>
<form id="RecoveryForm" method="post" action="exa.php">
<table align="center">
<tr>
<td>
<div class="input-append">
<input type="email" Required name="email" id="email" class="input-xlarge" placeholder="Email" maxlength="100" />
<span class="add-on"><li class="icon-envelope"></li></span>
<p id="mailerror"></p> <!-- This Segment Displays The Validation Rule For Email -->
</div>
</td>
</tr>
</table>
<input type="hidden" Readonly name="token" value="<?=Token::generate();?>" />
<center>
<input type="submit" id="submit" name="Forget" class="btn btn-primary" value="Submit" />
</center>
<script src="ajax/jquery-2.1.0.min.js"></script>
<script src="ajax/app.js"></script>
</form>
</body>
</html>
Second of all you are using jquery although this much much more easy to use i will suggest you start with java script validation, using the onsubmit attribute to catch the form and begin validation. you will be better understand what exactly is going on as a beginner rather than jquery.
<script>
$(function() {
/*Get FORM ID*/
var form = $('#RecoveryForm');
/*Get MESSAGE DIV ID */
var formMessages = $('#formresults');
/*Email Validation*/
var email_regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var email = $('#email').val();
if (!email.match(email_regex) || email.length == 0) {
$('#mailerror').text("* Please enter a valid email address *");
$("#email").focus();
return false;
}
else if (email.match(email_regex) && email.length >= 5){
$(form).submit(function(e) {
$( "#submit" ).prop( "disabled", false );
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
if (response.status=='Success'){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response.message);
}
else if (response.status=='warning'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
else if (response.status=='danger'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
else if (response.status=='info'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
/*Get FORM ID */
document.getElementById("RecoveryForm").reset();
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
$("#submit").removeAttr("disabled");
});
}
});
</script>
Third of all your PHP could have been better written but it works fine presumably :( so we leave that for now.
report different response with php validation
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><button type="button" class="close" data-dismiss="alert">×</button><d style="font-size:11px; ">' + messageText + '</d></div>';
(formMessages).html(alertBox);
For every PHP statement add:
$responseArray = array('type' => 'alert-warning', 'message' => '<b>Alert!</b>There is not enough credit');
Then send response json encoded
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray); header('Content-Type: application/json'); echo $encoded; } else { echo $responseArray['message']; }
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
Im facing a problem Notice: Undefined index: company in C:\xampp\htdocs\new_exp\login.php on line 4
Errors
At here i have 3 database. exp, new_1 and new_2. In exp database have company table which contain id, company_name, and database_name attributes.
There are two database connection that i use which are dbconnection_main.php and dbconnection.php. dbconnection_main.php i used to call ada database which storing company_name and database_name table. Once user selected option of company_name when login in same time it will call the database_name.
The error occur when i login.
This is my index.php
<?php
session_start();
error_reporting(-1);
// Cek Active Link
function ActiveClass($requestUri)
{
$current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
if ($current_file_name == $requestUri)
echo 'class="active"';
}
//check already login
if (!isset($_SESSION['UserId'])) {
header ('Location: login');
exit;
}
if ($_SESSION['level'] == 'APPROVAL'){
header ('Location: login');
exit;
}
//Link to page
if (isset($_GET['page']) && $_GET['page'] == 'ManageCategory') {
$page = "ManageExpenseCategory";
} else {
$page = 'dashboard';
}
//get global notification
include('includes/global.php');
//Get Header
include('includes/header.php');
//set global message notification
$msgBox ="";
if (file_exists('pages/'.$page.'.php')) {
// Load the Page
include('pages/'.$page.'.php');
} else {
// Else Display an Error
echo '
<div class="wrapper">
<h3>Err</h3>
<div class="alertMsg default">
<i class="icon-warning-sign"></i> The page "'.$page.'" could not be found.
</div>
</div>
';
}
include('includes/footer.php');
?>
So here is my login.php
<?php
session_start();
error_reporting(-1);
$_SESSION['db_company_name'] = $_POST['company'];
$msgBox = '';
//include notification page
include ('includes/notification.php');
//Include db Page
require_once ('includes/dbconnection.php');
//Include Function page
include ('includes/Functions.php');
//User Login
if(isset($_POST['login']))
{
$username = $mysqli->real_escape_string($_POST['email']);
$Password = encryptIt($_POST['password']);
if ($stmt = $mysqli->prepare("SELECT UserId, company_id, FirstName, LastName, Email, Password, level, admin_access, Currency from user WHERE Email = ? AND Password = ? "))
{
$stmt->bind_param("ss", $username, $Password);
$stmt->execute();
$stmt->bind_result($UserId_, $CompanyId_, $FirstName_, $LastName_, $Email_, $Password_, $Level_, $Admin_access_, $Currency_);
$stmt->store_result();
$stmt->fetch();
if ($num_of_rows = $stmt->num_rows >= 1)
{
session_start();
$_SESSION['UserId'] = $UserId_;
$_SESSION['FirstName'] = $FirstName_;
$_SESSION['LastName'] = $LastName_;
$_SESSION['level'] = $Level_;
$_SESSION['admin_access'] = $Admin_access_;
$_SESSION['Currency'] = $Currency_;
$_SESSION['company_id'] = $CompanyId_;
$compId = $_SESSION['company_id'];
$UserIds = $_SESSION['UserId'];
$company_q = mysqli_query($mysqli, "SELECT * FROM company_setting where company_id = '".$compId."'");
$company = mysqli_fetch_assoc($company_q);
$_SESSION['company_name'] = $company['company_name'];
if ($_SESSION['level'] === 'STAFF'){
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index">';
}
else
{
$msgBox = alertBox($LoginError);
}
}
}
}
?>
<!DOCTYPE html>
<html>
<div class="panel-body">
<?php if ($msgBox) {
echo $msgBox;
} ?>
<form class="form-horizontal m-t-20" method="post" action="" role="form">
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" onBlur="checkcompany(this.value)" type="email" required placeholder="<?php echo $Emails; ?>" name="email" id="email" autofocus>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" name="password" value="" required placeholder="<?php echo $Passwords; ?>">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<span id="result"><select name="company" id="company" class="form-control" required><option>company</option></select></span>
</div>
</div>
<div class="form-group text-center m-t-40">
<div class="col-xs-12">
<button type="submit" name="login" class="btn btn-primary btn-block text-uppercase waves-effect waves-light"><?php echo $SignIn; ?></button>
</div>
</div>
</form>
</div>
<script>
function checkcompany(v)
{
//alert(v);
var dataString = 'email='+v;
//document.getElementById('loginbtn').style.display = "none";
$.ajax({
type: "POST",
url: "checkaccount.php",
data: dataString,
cache: true,
success: function (result){
$("#result").html(result);
//document.getElementById('loginbtn').style.display = "block";
}
})
}
</script>
This is my checkaccount.php
<?php
error_reporting(-1);
session_start();
include("includes/dbconnection_main.php");
$email = $_POST['email'];
?>
<select name="company" id="company" class="form-control" required>
<option value="">----------------</option>
<?php
$company_q = mysqli_query($mysqli, "SELECT * FROM company");
while($company = mysqli_fetch_assoc($company_q))
{
//connect to sub database
$conn_hostname = "localhost";
$conn_database = $company['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqlii = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
$check_q = mysqli_query($mysqlii, "SELECT * FROM user WHERE Email = '".$email."' AND status = 'ACTIVE' AND password != ''");
$check = mysqli_num_rows($check_q);
if (!$check) {
printf("Error: %s\n", mysqli_error($mysqlii));
exit();
}
if($check >= 1)
{
?>
<option value="<?php echo $company['company_name']; ?>"><?php echo strtoupper($company['company_name']); ?></option>
<?php
}
mysqli_close($mysqlii);
}
?>
</select>
SO this is my dbconnection_main.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
?>
And This is my dbconnection.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
if(!isset($_SESSION))
{
session_start();
}
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}
$mysqlie = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
$get_database_q = mysqli_query($mysqlie, "SELECT * FROM company WHERE company_name = '".$company_name."'") or trigger_error(mysqli_error($mysqlie),E_USER_ERROR);
$get_database = mysqli_fetch_assoc($get_database_q);
if (!$get_database) {
printf("Errors: %s\n", mysqli_error($mysqlie));
exit();
}
$conn_hostname = "localhost";
$conn_database = $get_database['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqli = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
?>
I cannot detect the error since it only give me such general error prompt out. I think it might be related with dbconnection.php at this part which related with $_session..
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}
I have a comment system in which user comments and through ajax it validates the data and sent to .php page. The problem is it receives the status=1 but does not apply the else if Ajax code. I am stuck here. Any suggestions or help will be highly regarded.
AJAX
<script type="text/javascript">
$(document).ready(function() {
$("#submit_comment").click(function() {
var proceed = true;
$(" #comment_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed)
post_data = {
'user_email' : $('input[name=email]').val(),
'pid' : $('input[name=productid]').val(),
'msg' : $('textarea[name=comment]').val()
};
$.post('comments.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}
else if(response.status && response.type != 'error')
{
output = '<div class="success">'+response.text+'</div>';
$(response.html).hide().insertBefore('#comment_form').slideDown();
$(" #comment_form textarea[required=true]").val('');
$("#comment_form #comment_body").slideUp();
}
$("#comment_form #comment_results").hide().html(output).slideDown();
}, 'json');
});
//reset previously set border colors and hide all message on .keyup()
$("#comment_form input[required=true], #comment_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
</script>
Form
<?php
include "comment.php";
$comments = array();
$result = mysqli_query($con,"SELECT * FROM comments where product_id='$id' ORDER BY dt LIMIT 5");
while($row = mysqli_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
<?php
}
}
?>
<div class="form-style" id="comment_form">
<div id="comment_results"></div>
<div id="comment_body">
<input type="hidden" name="email" id="email" value="<?php echo $email?>">
<input type="hidden" name="productid" id="productid" value="<?php echo $pid?>" />
<label for="field5"><span>Comment: <span class="required">*</span></span>
<textarea name="comment" id="comment" class="textarea-field" required="true"></textarea>
</label>
<label>
<span> </span><input type="submit" id="submit_comment" value="Submit"">
</label>
</div>
</div>
comment.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
$this->data = $row;
}
public function markup()
{ $d = &$this->data;
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
// Needed for the default gravatar image:
return '
<div class="comment">
<div class="name">'.$d['email'].'</div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';
}
}
?>
comments.php
<?php
include("db/db.php");
include "comment.php";
if($_POST)
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_email"], FILTER_SANITIZE_STRING);
$pid = filter_var($_POST["pid"], FILTER_VALIDATE_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$arr = array();
//additional php validation
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
mysqli_query($con,"INSERT INTO comments(email,body,product_id) values('$user_name','$message','$pid')");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
$res=mysqli_query($con,$query);
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
if(!$res)
{
$output = json_encode(array('type'=>'error', 'text' => 'Cannot recieve your comment.'));
die($output);
}else{
$output= json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your review','status'=>1,'html'=>$insertedComment->markup()));
echo $output;
die($output);
}
}
?>
I have an update password page that won't let me enter the actual current password for the current password field. Instead, it wants the hashed password. Once changed however, the new one is then hashed, which is a good thing. I just need to be able to enter the actual password and not hashed.
Yes I know, no md5; this is more for testing is all.
changepassword.js
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
</script>
updatepassword.php
<?php
include 'core/login.php'; === this contains the connection, it's obviously good ===
include 'includes/head.php'; === changepassword.js is linked in the head ===
if(count($_POST)>0) {
$result = mysqli_query($link, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
if($_POST["currentPassword"] == $row["password"]) {
mysqli_query($link, "UPDATE users set `password`='" .md5(md5($_POST['newPassword'])) . "' WHERE id='" . $_SESSION["id"] . "'");
$message = "Password Changed";
} else $errormessage = "Current Password is not correct";
}
print_r($_SESSION);
?>
form on same page:
<div class="container">
<div class="text-center">
<h4>Change password below</h4>
</div><br />
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="message"><?php if(isset($errormessage)) { echo $errormessage; } ?></div>
<div class="col-md-4 col-md-offset-4">
<form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<div class="form-group">
<label>Current Password*</label>
<input type="text" name="currentPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>New Password*</label>
<input type="text" name="newPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>Confirm Password*</label>
<input type="text" name="confirmPassword" class="form-control input-md" />
</div>
<br />
<div class="text-center">
<input type="submit" name="submit" class="btn btn-success" value="Submit" />
</div>
</form>
</div>
</div>
Your problem is here:
if($_POST["currentPassword"] == $row["password"]) {
You are comparing the actual text version of the hash (say "password") to the hashed version of that password (say "213y789hwuhui1dh"). This evaluates out to:
if("password" == "213y789hwuhui1dh") {
Which obviously is never accurate. All you have to do to solve the problem is hash the password in the same way you did when you created it. If I understand your code properly, that should be:
if(md5(md5($_POST["currentPassword"]))==$row["password"]) {
SIDE NOTE ON SQL INJECTION
Please note that this code would be super easy to inject into. All a user would have to do is end the "currentPassword" POST value with '; SHOW DATABASE; and they would have unlimited access to your server's MySQL database. Consider learning to use MySQLi Prepared Statements. They are easy to understand, and easy to implement.
I went overboard. Your other question was closed. Juuuuust gonna leave this here... I'm using PHP version PHP 5.2.0.
http://php.net/manual/en/faq.passwords.php
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
<?php
// so I don't actually have to test form submission, too...
$_POST['current_password'] = 'Tacotaco';
$_POST['new_password'] = 'NINrocksOMG';
$_POST['confirmPassword'] = 'NINrocksOMG';
$_SESSION['id'] = 1;
// this is Tacotaco encrypted... update your db to test
// update users set password = '$2y$10$fc48JbA0dQ5dBB8MmXjVqumph1bRB/4zBzKIFOVic9/tqoN7Ui59e' where id=1
// the following is sooooo ugly... don't leave it this way
if (!isset($_SESSION['id']) or empty($_SESSION['id']) or
!isset($_POST['current_password']) or empty($_POST['current_password']) or
!isset($_POST['new_password']) or empty($_POST['new_password']) or
!isset($_POST['confirmPassword']) or empty($_POST['confirmPassword']) ) {
$message = 'Please enter your password';
}
else {
$sid = $_SESSION['id'];
$currpass = $_POST['current_password'];
$newpass = $_POST['new_password'];
$conpass = $_POST['confirmPassword'];
$message = validate_password($sid, $currpass, $newpass, $conpass);
}
print "<br/>$message<br/>";
function validate_password($sid, $currpass, $newpass, $conpass) {
$mysqli = mysqli_connect('localhost','root','','test')
or die('Error ' . mysqli_error($link));
$stmt = $mysqli->prepare('select id, password from users where id = ?');
$stmt->bind_param("s", $sid);
$stmt->execute();
$stmt->bind_result($userid, $userpass);
$message = '';
if ($stmt->fetch()) {
$stmt->close();
if (strlen($newpass) < 8) {
$message = 'Please enter a password with at least 8 characters';
}
elseif (!preg_match('`[A-Z]`', $newpass)) {
$message = 'Please enter at least 1 capital letter';
}
elseif ($newpass !== $conpass) {
$message = 'Your passwords do not match.';
}
else {
if (password_verify($currpass, $userpass)) {
$hashed_new = password_hash($newpass, PASSWORD_BCRYPT);
$query = 'update users set password = ? where id = ?';
$stmt_new = $mysqli->prepare($query);
$stmt_new->bind_param('ss', $hashed_new, $sid);
if ($stmt_new->execute()) {
$message = 'Password Changed';
}
else {
$message = $mysqli->error;
}
}
else $message = 'Current Password is not correct';
}
}
else {
$message = 'user not found for id $sid';
}
$mysqli->close();
return $message;
}
?>