How to fix sign_in error? - php

I am facing error in my code. My problem is not allowing signin at the home page. The database is working fine. The validation is fine. The problem is in script of login page. It is showing an error only in the success portion.
Here are my files:
login1.php
<!DOCTYPE html>
<?php
include('header.php');
?>
<html>
<head>
<title>Login screen</title>
<script type="text/javascript" src="script/validation.min.js"></script>
<script type="text/javascript" src="script/login.js"></script>
<link href="css1/style_log.css" rel="stylesheet" type="text/css" media="screen">
</head>
<body>
<div class="container">
<h1 align=center></h1>
<h2 align=center style="color:purple";> </h2>
<form class="form-login" method="post"name="Loginform" action="" id="login-form">
<h2 class="form-login-heading">User Log In Form</h2>
<hr />
<div id="error"></div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name="userEmail" id="user_email" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-success" name="submit" id="login_button">
<span class="glyphicon glyphicon-log-in"></span> Sign In
</button>
</div>
<div class="form-group">
<button class="btn btn_success"> Sign up</button>
<button class="btn btn_success"> <a href="forget_password.php"style="text-decoration: none;" >Forget password?</a></button>
<button class="btn btn_success">Reset password </button>
</form>
</div>
</div>
</div>
</body>
</html>
login1_action.php
<?php
session_start();
include'connect.php';
if(isset($_POST['submit'])& !empty($_POST)){ //check the input is post or not
$email=(strip_tags($_POST['userEmail'])); //post the input.
$password=md5(strip_tags($_POST['password']));
require"connect.php";
echo $q="select password,useremail from users where password='$password' and useremail='$email'"; //select the data from table for validation
$result=mysqli_query($con,$q);
$row=mysqli_fetch_assoc($result);
if($row['password']==$password){
echo "ok";
exit;
$_SESSION['user_session'] = $row['serialno'];
} else {
echo "email or password does not exist."; // wrong details
}
}
?>
login.js
$('document').ready(function() {
/* handling form validation */
$("#login-form").validate({
rules: {
password: {
required: true,
},
userEmail: {
required: true,
email: true
},
},
messages: {
password:{
required: "please enter your password"
},
userEmail: {required: "please enter your password"},
},
submitHandler: submitForm
});
/* Handling login functionality */
function submitForm() {
var data = $("#login-form").serialize();
$.ajax({
type : 'POST',
url : 'login1_action.php',
data : data,
beforeSend: function(){
$("#error").fadeOut();
$("#login_button").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(response){
if(response=="ok") {
$("#login_button").html('<img src="ajax-loader.gif" /> Signing In ...');
setTimeout(' window.location.href = "index1.php"; ',4000);
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
$("#login_button").html('<span class="glyphicon glyphicon-log-in"></span> Sign In');
});
}
}
});
return false;
}
});

In login1.php:
You have a semicolon outside your style value on <h2>. Pull it inside the double quote.
You have one too many </div>'s at the end and your </form> is out of nesting order.
In login1_action.php:
Your first condition statement only has one & in the between the two conditions. Change this to &&.
You are using exit before you declare the $_SESSION data. Move exit after the declaration.
Your query is not injection-safe. I advise you to use a prepared statement.
You are not calling the serialno column in your query, but you are asking for the value from the resultset when you are declaring the $_SESSION['user_session'] value.
Here is a new block of code using a prepared statement:
if($stmt=$con->prepare("SELECT `serialno` FROM `users` WHERE `useremail`=? AND `password`=?;")){
// stripping tags will do nothing to protect you
$email=$_POST['userEmail'];
$password=md5($_POST['password']);
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($serialno);
if($stmt->fetch()){
$_SESSION['user_session']=$serialno;
echo "ok";
$stmt->free_result();
}else{
echo "Incorrect Username/Password Combination"; // Query Logic Error
}
$stmt->close();
}else{
echo "Query Syntax Error"; // echo mysqli_error($con);
}
And I recommend that you replace your md5() function.
Reading: Why not use MD5 for password hashing?

Related

Not logging into another page using PHP and Ajax using sessions

I am using PHP and Ajax to logging into another page with session variable. When I click submit button nothing happen.
The HTML code are following named as login.php:
<?php
require_once "dbconnection.php";
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: index.php");
exit;
}
?>
<div id='info'> </div>
<form method="POST" class="form-signin" name="mylogin" id="mylogin">
<div class="account-logo">
<img src="assets/img/logo-dark.png" alt="">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="email" name="email" autofocus="" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" id="password" class="form-control">
</div>
<div class="form-group text-right">
Forgot your password?
</div>
<div class="form-group text-center">
<input type="button" value="login" id="login" name="login"
class="btn btn-primary account-btn" >
</div>
<div class="text-center register-link">
Don’t have an account? Register Now
</div>
</form>
In the same page Ajax query is:
<script>
$(document).ready(function (){
$('#mylogin').validate({
rules: {
password:{
required:true;
},
email:{
required:true;
email:true
}
},
messages: {
password:{
required:"Requered"
},
email:"Requered"
},
submitHandler : subform
})
function subform() {
var email = $('#email').val();
var password = $('#password').val();
var data = {
"email": email,
"password": password
$.ajax({
type: "POST",
url: "auth/logging.php", // Url to which the request is send
data: data,
// Type of request to be send, called as method
beforeSend:function () {
$('#info').fadeOut();
$('#login').html('Sending ....');
},
success: function(resp){
if(resp=="ok"){
$('#login').html('Login');
setTimeout('window.location.href="index.php";',4000);
}else{
$('#info').fadeIn(1000,function(){
$('#info').html("<div class='alert alert-danger'>" +resp+ "</div>");
$('#login').html('Login');
})
}
}
})
}
})
</script>
My logging.php would be:
<?php
session_start();
require_once "dbconnection.php";
if (isset($_POST['email'])) {
$email = trim($_POST["email"]);
$pass = trim($_POST["password"]);
$password = md5($pass);
$query = $mysqli->prepare("SELECT * FROM users WHERE email=?");
$query->bind_param("d",$email);
$query->execute();
$query->bind_result($id,$user,$myemail,$mypass);
$query->fetch();
if($mypass==$password){
echo 'ok';
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
}else{
echo 'emai & pass wrog';
}
?>
Any help may appreciated.
It should be s instead of d. It stands for string.
$query->bind_param("s",$email);
Also you should never use MD5 for passwords. Use password_hash()

redirect is not going to separate page

I have a sign in page that uses Ajax to send username and password to a php file to verify. If the verification fails, it sends a message back to the user stating this on the sign in page under the create account button. This is good. If the user/password is correct, I want to redirect to the users account page. This is working also, but it is ending up in the same place as the failed verification - on the sign in page under the create account button. I understand why this is happen, I am not sure how to get the redirect to just show the new page on it's own page. Thanks
See for yourself - kyzereyephotography.com/examples/signIn/signIn.php
username/pass - 123#123.com / 123
use an incorrect password to see the failed message
Here is the code:
signIn.php
<!DOCTYPE html>
<html>
<head>
<title>Sign IN</title>
<link href="../dist/css/bootstrap.css" rel="stylesheet">
<link href="../dist/css/signin.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<!-- Fixed navbar -->
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="../">Code Example - Log In</a>
</div>
</div>
</div> </br></br>
<!-- Sign In Form -->
<div class="container">
<form class="form-signin" id="login_form" action="checkLogin.php" method="post">
<p>
This bit of code asks you to log in. If you do not have an account, you can create one and then log on to it.
</p>
<h2 class="form-signin-heading">Please sign in</h2>
<input name="username" id="username" type="text" class="form-control" placeholder="Email address" required autofocus>
<input name="password" id="password" type="password" class="form-control" placeholder="Password" required>
<button id="signin" class="btn btn-lg btn-primary btn-block" type="submit" >Sign in</button>
</form>
<!-- Create Accout Form -->
<form class="form-signin">
<input class="btn btn-lg btn-primary btn-block" type="button" value = "Create Account" onclick="window.location.href='createAccount.php'"/>
</form>
<span id="badpass"></span> <!--place to put the error message if password or username is bad-->
</div> <!-- /container -->
<!-- JavaScript-->
<!-- this script is used to validate the username and password. JavaScript is used to pass data to checklogin.php-->
<script type="text/javascript">
$("#signin").click( function() {
var data = $("#login_form :input").serializeArray();
$.post( $("#login_form").attr("action"), data, function(info) { $("#badpass").html(info);});
});
$("#login_form").submit(function() {
return false;
});
</script>
</body>
</html>
checkLogin.php
<?php
session_start();
include "includes/dbconnect.php";
$username = $_POST['username'];
$userPassword = $_POST['password'];
$query1 = "SELECT first_name, last_name, password FROM profiles WHERE email = '$username'";
$results1 = mysql_query($query1,$dbconnect) or die ("Error in query1. ". mysql_error($dbconnect));
$row = mysql_fetch_assoc($results1);
$count = mysql_num_rows($results1);
$hashedPass = $row['password'];
if($count == 1)
{
if (crypt($userPassword, $hashedPass) == $hashedPass)
{
$_SESSION["username"] = $username;
header("location: profilesPage.php");
die();
}
else
{
echo "<div style='color: red; font-size: 20px; text-align: center;'>ID or Password does not match</div>";
}
exit();
}
else
{
echo "<div style='color: red; font-size: 20px; text-align: center;'>Bad username or password</div>";
}
?>
First of all: Please update your script to MySQLi() or PDO() for security reasons! Mysql is deprecated!
Next my approach for your problem would be something like this:
$("#signin").click( function() {
var data = $("#login_form :input").serializeArray();
$.post(
$("#login_form").attr("action"),
data,
function(info) {
if(info == ""){ //Insert good password response here
window.location.href = ""; //Url to profile page here
} else {
$("#badpass").html(info);
}
}
);
});

Jquery php mysql login does send data to mysql but doesn't return right value?

Question: I can see that the data is getting written to the database but $action doesn't become register in the insert.php call from the html file and hence php JSON return is NULL ??
<!DOCTYPE html>
<html>
<head>
<title>Load </title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
Register
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="registerp">
<div data-theme="a" data-role="header">
<h3>Register</h3>
</div>
<div data-role="content">
<form id="registerform" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="fname">First Name:</label>
<input type="text" value="" name="fname" id="fname"/>
</div>
<div data-role="fieldcontain">
<label for="lname">Last Name:</label>
<input type="text" value="" name="lname" id="lname"/>
</div>
<div data-role="fieldcontain">
<label for="uname">User Name:</label>
<input type="text" value="" name="uname" id="uname"/>
</div>
<div data-role="fieldcontain">
<label for="pwd">Enter your password:</label>
<input type="password" value="" name="pwd" id="pwd"/>
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input type="text" value="" name="email" id="email"/>
</div>
<input type="button" data-theme="b" name="submit" id="register" value="Register">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>Welcome Page</h3>
</div>
<div data-role="content">
Welcome
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<script type="text/javascript">
$(document).on('pageinit', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: "action=login&" + $('#check-user').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert('Log on unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
<script type="text/javascript">
$(document).on('pageinit', '#registerp', function(){
$(document).on('click', '#register', function() {
if($('#uname').val().length > 0 && $('#pwd').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'insert.php',
data: "action=register&" + $('#registerform').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert(' Try again later ! Server is busy !');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
</body>
</html>
While my PHP Script is simple as shown below... please help
<?php
$con=mysqli_connect("...............", "...........", ".........","........");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['pwd']);
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES ('$uname', '$fname', '$lname', '$password','$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
if($action == 'register'){
$output = array('status' => true, 'message' => 'Registered');
}
echo json_encode($output);
?>
Insert php script doesnt work while the below register php script works fine.
<?php
// We don't need action for this tutorial, but in a complex code you need a way to determine Ajax action nature
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
// Get username
$username = $_POST['username'];
// Get password
$password = $_POST['password'];
$db = #mysql_connect('..........', '........', '..........') or die("Could not connect database");
#mysql_select_db('users', $db) or die("Could not select database");
$result = mysql_query("SELECT `password` FROM `userdb` WHERE `username`= '$username'");
$r = mysql_fetch_assoc($result);
$pass_ret = $r['password'];
// Lets say everything is in order
if($action == 'login' && $password == $pass_ret){
$output = array('status' => true, 'message' => 'Login');
}
else
{
$output = array('status' => false, 'message' => 'No Login');
}
echo json_encode($output);
?>
You should use Chrome Dev Tools or Firebug in Firefox to inspect the response from the AJAX call. You set the call to expect JSON as the data type and you also use it as JSON. The problem is you have this line:
echo "1 record added";
Which is output before your JSON. So your response probably looks something like:
1 record added{"status": false, "message": "No Login"}
This isn't valid JSON and it will not parse, and thusly this line will never work:
if(result.status) {

jQuery validation on form not working

I'm new to jQuery and I'm trying to use it to validate a login form. However, the validation script doesn't activate: it just sits there doing nothing, while disabling the submit button. I think it is interfering with another script running on the same form, which lets the user switch between different forms in the same div.
Here's the html:
<div class="box">
<?php if (isset($_SESSION['login'])){ ?>
<h2>Welcome back, <?php echo $_SESSION['username']; ?></h2>
<div><p>Click here to log outt</p></div>
<?php } else { ?>
<div id="form_wrapper" class="form_wrapper">
<div class="register"> <!-- First form -->
<form id="registrationform">
<h2>Register</h2>
<div class="box">
<div>
<label>Name:</label>
<input name="nomeagenzia" type="text" required />
</div>
<!-- Some other input fields -->
<input type="submit" value="Register" />
Already a user? Login here
</div>
</form>
</div>
<div class="login active"> <!-- Second form, the one I'm validating-->
<form id="loginform" action="index.php" method="POST">
<h2>Area Agenzie</h2>
<div class="box">
<div>
<label>Username:</label>
<input name="username" type="text" />
</div>
<div style="position:relative;">
<label>Password:</label>
Forgot your password?
<input name="password" type="password" />
</div>
<input name="submit" type="submit" value="Login" />
Register here!
</div>
</form>
</div>
<!-- There's a third form I omitted -->
</div>
<?php } ?>
</div>
Here is the javascript to switch between the forms:
$(function() {
var $form_wrapper = $('#form_wrapper'),
$currentForm = $form_wrapper.children('div.active'),
$linkform = $form_wrapper.find('.linkform');
$form_wrapper.children('div').each(function(i){
var $theForm = $(this);
if(!$theForm.hasClass('active'))
$theForm.hide();
$theForm.data({
width : $theForm.width(),
height : $theForm.height()
});
});
setWrapperWidth();
$linkform.bind('click',function(e){
var $link = $(this);
var target = $link.attr('rel');
$currentForm.fadeOut(100,function(){
$currentForm.removeClass('active');
$currentForm= $form_wrapper.children('div.'+target);
$form_wrapper.stop()
.animate({
width : $currentForm.data('width') + 'px',
height : $currentForm.data('height') + 'px'
},225,function(){
$currentForm.addClass('active');
$currentForm.fadeIn(100);
});
});
e.preventDefault();
});
function setWrapperWidth(){
$form_wrapper.css({
width : $currentForm.data('width') + 'px',
height : $currentForm.data('height') + 'px'
});
}
});
Here's the validation script:
$(document).ready(function()
{
$("#loginform").validate(
{
rules:{
'username':{
required: true,
remote:{
url: "php/validatorAJAX.php",
type: "post"
}
},
'password':{
required: true
}
},
messages:{
'username':{
required: "Il campo username è obbligatorio!",
remote: "L'username non esiste!"
},
'password':{
required: "Il campo password è obbligatorio!"
}
},
submitHandler: function(form){
if($(form).valid())
form.submit();
return false;
}
});
});
Finally, this is validatorAJAX.php included in the validation script:
<?php
$mysqli = new mysqlc();
function usernameExists($username){
$username = trim($username);
$stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM utenti WHERE username= ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($result);
$result = (bool)$stmt->fetch();
$stmt->close();
return $result;
}
if(isset($_POST['username'])){
if(usernameExists($_POST['username'])){
echo 'true';
}else{
echo 'false';
}
}
?>
You can test out the script at http://pansepol.com/NEW, and you'll see that nothing happens when you click "Submit" on the login_form. Moreover, no validation is done whatsoever. I'm going nuts here :)
I fixed it: there was a problem with the validatorAJAX.php, which causes the whole form to crash. Basically the mysqli object was initialized outside the function, and this caused the validation to fail.

save fields in data base throught Ajax

i have 2 files :
- form.php :
<html>
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function()
{
$('#r').click(function()
{
pseudo= $("#pseudo").val();
password= $("#password").val();
$.ajax({
type:"POST",
url:"insert.php",
data:'pseudo='+pseudo+'&password='password,
success:function(data)
{
if(data == 1)
{
alert("ddd");
}
else
{
alert("lll");
}
}
});
});
});
</script>
</head>
<body>
<center>
<form class="well form-inline" method="post" action="buscarUsuario.php">
<a class="btn btn-danger" href="" id="r">Save</a>
<input type="text" style="height: 30px" class="span4" placeholder="Pseudo" id="pseudo" />
<span id="error"></span>
<span id="ok"></span>
<input type="password" style="height: 30px" class="span4" placeholder="Password" id="password"/>
<button type="submit" style="width: 95px" class="btn btn-primary" value="Entrar" name="Entrar">Entrar</ button>
</form>
<center>
</body>
</html>
and i want to save pseudo and password in my data base through this file insert.php :
<?php
require "connecttoBD.php";
$pseudo= $_POST["pseudo"];
$password= $_POST["password"];
$sql="INSERT INTO usuarios (pseudo,password) VALUES ('$pseudo,$password') ";
$req=mysql_query($sql) or die (mysql_error());
echo "1";
?>
but when i fill out the 2 fields and press the button Save I have not saved the 2 fields in my data base.
can anyone help me please ?
thank you.
data:'pseudo='+pseudo,
change in
data:{ pseudo:pseudo,
password:password
},
in your ajax request
try
$sql="INSERT INTO usuarios (pseudo,password) VALUES ('$pseudo','$password') ";
$req=mysql_query($sql) or die (mysql_error());
and insted of
if(data == 1)
use
if($.trim(data) == 1)

Categories