redirect is not going to separate page - php

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);
}
}
);
});

Related

Why would my PHP session variables only work in specific browsers and fail in others?

So i am trying to set up a basic user login form. I want to compare the inputs to the existing database. Everything works fine in Firefox. All information is passed. But in : Chrome, Safari, IE. Almost anything else i'm trying. None of the Session data passes?
For instance.
This is my existing code. It works perfectly in Firefox
login.php
<?php
require_once('../../config/sessionHandler.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script src="JavaValidate.js" type="text/javascript"></script>
<title>Login</title>
</head>
<body>
<div class="container">
<form class="form-horizontal" role="form" id="logForm" name="logForm" method="POST" action="ajax.php">
<div id="userName-group" class="form-group">
<label for="txtUserName" class="col-sm-2 control-label">User Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUserName" name="txtUserName" placeholder="User Name" maxlength="9">
</div>
</div>
<div class="form-group">
<label for="txtPasswordInput" class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword" name="txtPassword" placeholder="Password" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnLogout" onclick="location.href = 'logout.php';" name="logout" type="button" value="logout" class="btn btn-primary">
</div>
</div>
</form>
</div>
</body>
</html>
I have some basic HTML with 2 inputs. Username and Password
This utilizes 3 files. my ajax.php, sessionHandler.php, and my JavaValidate.js
sessionHandler.php
<?php
if(session_status() === PHP_SESSION_NONE)
{
session_start();
}
$userName= $_SESSION['UserName'];
?>
JavaValidate.js
$(document).ready(function()
{
$('#logForm').submit(function(event)
{
var logData = {
'userName': $('input[name=txtUserName]').val(),
'password': $('input[name=txtPassword]').val(),
}
$.ajax({
type : 'POST',
url : 'ajax.php',
data : logData,
dataType : 'json',
encode : true
})
.done(function(data)
{
if(!data.success)
{
if (data.errors.userName)
{
$('#userName-group').addClass('has-error');
$('#userName-group').append('<div class="help-block">' + data.errors.userName+ '</div>');
}
}
else
{
//APPEND SUCCESS
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
}
})
.fail(function(data)
{
});
event.preventDefault();
});
});
ajax.php
<?php
require_once('../../config/sessionHandler.php');
//VARIABLE DECLARATION
$formdata = array();
$inputString = $_POST['userName'];
$inputPass = $_POST['password'];
$data['message'] = 'Success!';
$_SESSION['UserName'] = $inputString;
$_SESSION['Password'] = $inputPass;
$_SESSION['Errors'] = $errors['userName'];
echo json_encode($data);
?>
When i run this in different browsers i get different results? After i submit the form with the following data:
FireFox
Input: "Username", "Password1"
$_SESSION['Username'] = Username
$_SESSION['Password'] = Password1
Google Chrome
Input: "Username", "Password1"
$_SESSION['Username'] = Username
$_SESSION['Password'] = NULL
Safari Browser (On my phone)
Input: "Username", "Password1"
$_SESSION['Username'] = Username
$_SESSION['Password'] = NULL
For some reason this seems to work exactly as expected on FireFox? yet it seems to go wonky in every other browser. I'm not sure if i am just missing something for different browsers reading Session data differently? For some reason my password session is only visible through firefox? I thought i might use session data to keep it somewhat hidden before hasing.
If anyone could help shed some light on this for me it would be greatly appreciated! Thank you all for your time!

How to fix sign_in error?

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?

AJAX form Validation Error

I'm developing a simple login form but with advanced features in that. On submitting the form I want to validate it with AJAX and display the error message in the respective "SPAN class="error". The problem is i'm not getting the validation error when i submit the form. The following is the code i've tried. Please help..
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="_images/Favicon.png"/>
<title>18+</title>
<link href="_css/login.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="_scripts/jquery.tools.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').focus(); Focus to the username field on body loads
$('#submit').click(function(){ // Create `click` event function for login
var username = $('#username'); // Get the username field
var password = $('#password'); // Get the password field
var login_result = $('.login_result'); // Get the login result div
var username = $('.username'); // Get the username error div
var password = $('.password'); // Get the password error div
if(username.val() == ''){ // Check the username values is empty or not
username.focus(); // focus to the filed
username.html('<span class="error">Enter the Username...</span>');
return false;
}
if(password.val() == ''){ // Check the password values is empty or not
password.focus();
password.html('<span class="error">Enter Your Password...</span>');
return false;
}
if(username.val() != '' && password.val() != ''){
var UrlToPass = 'action=login&username='+username.val()+'&password='+password.val();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type : 'POST',
data : UrlToPass,
url : 'checker.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
login_result.html('<span class="error">The Username Or Password You Entered Is Incorrect...</span>');
}
else if(responseText == 1){
window.location = 'admin.php';
}
else{
alert('Problem with sql query');
}
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="logo"></div>
<div id="container">
<div id="form">
<form action="" method="post" id="user_login" name="user_login" enctype="multipart/form-data">
<p id="head">User Login</p>
<div class="row">
<span class="error" class="login_result" id="login_result"></span>
</div>
<div class="row">
<div class="input">
<input type="text" id="username" name="username" class="detail" placeholder="Username" spellcheck="false" title="Enter Your Username.."/>
<span class="error" id="username">Enter Your Username....</span>
</div>
</div>
<div class="row">
<div class="input">
<input type="password" id="password" name="password" class="detail" placeholder="Password" spellcheck="false" title="Enter Your Password.."/>
<span class="error" id="password">Enter Your Password...</span>
</div>
</div>
<p class="submit">
<button type="submit" id="submit" name="submmit" value="Register">Login</button>
</p>
</form>
</div>
</div>
</div>
</div><!--end container-->
<div id="formfooter">
<div class="input">
Copyright © CompanyName.
</div>
</div>
</body>
</html>
You should prevent the default action when you catch the event in javascript:
....
$('#submit').click(function(e){ // Create `click` event function for login
e.preventDefault(); //Prevent the default submit action of the form
var username = $('#username'); // Get the username field
var password = $('#password'); // Get the password field
var login_result = $('.login_result'); // Get the login result div
....
First, you have two same ids on your HTML form.
<input type="text" id="username" .../>
<span class="error" id="username">....
Take a look above and you can see that there are two ids username. You should change the id attribute with class attribute so it become
<span class="error" class="username">....
Second, on your javascript you have same variables assigning.
var username = $('#username');
var password = $('#password');
.....
var username = $('.username');
var password = $('.password');
Username and password are already taken. Change that into different variable name.
Third, I suggest you to use this awesome jquery form validation library http://jqueryvalidation.org/
Good luck :)

What is wrong with my form via Ajax to PHP?

Been scouring this site and find many AJAX to PHP examples but following these I cannot figure why on earth my scripts are not working.
I have an HTML form with a button. You click the button it calls a Bootstrap modal window. You enter an email address click Submit.
It posts to a PHP file that will email me.
The reason I am implementing using AJAX is because I do not want the ACTION and METHOD submit on the form. I want to submit via AJAX so the user is not redirected to my PHP page.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"> </script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
<script>
$(document).ready(function () {
$("button#submit").click(function(){
$.ajax({
type: "POST",
url: "email.php", //
data: $('form.icontact').serialize(),
success: function(msg){
$("#thanks").html(msg)
$("#contact").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
</script>
</head>
<body>
<div class="container"> <!-- numbers cannot total more than 12 for rows-->
<div id="thanks"><p>Submit!</p></div>
</div>
<!--contact modal-->
<div class="modal fade"id="contact" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class ="form-horizontal" name="icontact" id="icontact">
<div class="modal-header">
<h4>testemail</h4>
</div>
<div class="modal-body">
<p>Please enter your email address and click submit to receive your free first chapter</p>
<div class="form-group">
<label for ="contact-email" class="col-lg-2 control-label">Email: </label>
<div class="col-lg-10">
<input type="email" class="form-control" id="fromaddress" placeholder="new#example.com" name="fromaddress" />
<input type="hidden" id ="subject" value="enter in your email" name="subject" />
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal">Cancel</a>
<button class="btn btn-primary" type="submit" id="submit">Send</button>
</div>
</form>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script src="js/bootstrap.js"></script>
</body>
and here is the php file. I get failure when I run it and it is passing the data in the URL like a GET. What am I doing wrong?
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
if (isset($_POST["fromaddress"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["fromaddress"]);
if ($mailcheck==FALSE) {
echo "Invalid input";
} else {
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!</span><br><br>";
$from = strip_tags($_POST["fromaddress"]); // sender
$subject = strip_tags($_POST["subject"]);
$message = "Thanks.";
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("test#test.com",$subject,$message,"From: $from\n");
}
}
?>
The problem is, you form is submitting either ways. You haven't prevented the default behaviour of the submit button. i.e. Submitting the form and redirecting to the form-action.
Do something like this
$("button#submit").click(function(e){
e.preventDefault(); // This line avoids the default submit event.
//Rest of stuff as you have it.....
});
A better option is to do the AJAX call on the .submit() rather than on the .click() as below
$("form#icontact").submit(function(e){
e.preventDefault();
//Proceed with other stuff as is...
});
Hope this helps! :)

Return value from ajax form

I have a login form in php. I have used ajaxform so that the page does not get reloaded when the username or password is wrong. I have another page checklogin.php which checks whether the username and pw is there in the database and it returns the count of the number of rows. I want to compare the count in the login.php and display the error message if the count=1 and redirect to another page if count=2. I tried to display the count in an errordiv using target: 'errordiv' and checking its innerHTML but it failed to do so.
My login.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.form.js"></script>
<!--Slider-in icons-->
<script type="text/javascript">
function checklogin()
{
var request=$("#login-form").ajaxForm(
{
target:'#errordiv'
}).abort();
request.submit();
var divmsg=document.getElementById("errordiv");
if (divmsg.childNodes[0].nodeValue == "1")
{
divmsg.childNodesp[0].nodeValue="Sorry";
alert ("Invalid username or password");} //I didn't get the alert as well a the divmsg content didn't change
};
</script>
</head>
<body>
<!--WRAPPER-->
<div id="wrapper">
<!--LOGIN FORM-->
<form name="login-form" id="login-form" class="login-form" action="checklogin.php" method="post">
<!--CONTENT-->
<div class="content">
<!--USERNAME--><input name="un" type="text" class="input username" placeholder="Username" onfocus="this.value=''" required="required" /><!--END USERNAME-->
<!--PASSWORD--><input name="pw" type="password" class="input password" placeholder="Password" onfocus="this.value=''" required="required" /><!--END PASSWORD-->
</div>
<!--END CONTENT-->
<!--FOOTER-->
<div class="footer">
<!--LOGIN BUTTON--><input type="submit" name="submit" value="Login" class="button" onclick="checklogin()" /><!--END LOGIN BUTTON-->
</div>
<!--END FOOTER-->
</form>
<div id="errordiv" class="errordiv"></div>
<!--END LOGIN FORM-->
checklogin.php
<?php
include ('dbconn.php');
$user = trim($_POST['un']);
$pass = trim($_POST['pw']);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$result=mysql_query("select Id from login where Username='$user' and Password='$pass'") or die (mysql_error());
$result= mysql_fetch_assoc($result);
$num= count ($result);
echo $num;
?>
How can I get the value of $num in login.php without displaying it to a div and compare the value of $num and accordingly display the errormsg in errordiv or if $num==2 redirect to another page.
Change your code to include the code which change the div and provide alert to be included in the callback.
var request=$("#login-form").ajaxForm(
{
target:'#errordiv',
success: function (html) {
if ($("#errordiv).html() == "1") {
$("#errordiv).html("Sorry");
alert ("Invalid username or password");
}
}
}).abort();
request.submit();
Maybe try to make the checking request asynchronously and process user feedback in AJAX callback:
JS:
$(function(){
$("#login-form").ajaxForm(function(response){
if(response.count===1){
$("#errordiv").html("msg you want to show");
}else if(response.count===2){
//redirect
}
});
});
php:
<?php
header("Content-Type: application/json");
//your database check logic
$user = trim($_POST['un']);
$pass = trim($_POST['pw']);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$result=mysql_query("select Id from login where Username='$user' and Password='$pass'") or die (mysql_error());
$result= mysql_fetch_assoc($result);
$num= count ($result);
//and return response in JSON
echo json_encode(array("count"=>$num));
?>
Hope this is helpful for you.
[EDIT]
remove the form submit button inline JS function invoking:
onclick="checklogin()"
and put checklogin function logic to document ready callback, initialize the form when the DOM is ready

Categories