PHP and AJAX Log in validation - php

I need some help troubleshooting my code that's used for Log In validation. It's a combo of AJAX and PHP.
Here's the AJAX code that's directly in the login page.
<script language="javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.post("/ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val()
,rand:Math.random() } ,function(data)
{
if (data=='no')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Incorrect Username or Password.')
.addClass('messageboxerror').fadeTo(900,1);
}
);
}
else if(data=='yes')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Logging in.....').addClass('messageboxok').fadeTo
(900,1, function()
{
document.location='/mainpage.php';
}
);
}
);
}
else
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('User is already logged in.').
addClass('messageboxerror').fadeTo(900,1);
}
);
}
});
return false;
});
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
});
</script>
PHP CODE:
<?
//Log In credentials
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y'){echo "alreadyLogged"; exit;}
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate=mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
}
else
{echo "no";}
?>
To summarize this process, someone logs in and the PHP script checks
if the username and password is valid AND that the person is NOT logged in already - returns value of 'yes'
if the username and password is valid AND that the person IS logged in already - returns value of 'alreadyLogged'
Invalid username or password - returns value of 'no'
This gets passed to AJAX, which SHOULD display the correct messages based on the return values from the php script. For reference (using the above summary):
AJAX should return: Logging in...
AJAX should return: User is already logged in.
AJAX should return: Invalid Username or Password.
The problem is this: If someone logs in correctly and IS NOT already logged in, message 2 appears instead of message 1. (I think that message 1 may appear but it disappears so fast).
I think the culprit is AJAX but unfortunately I'm not as familiar with it as I am with PHP.

I think the problem is with your php code.Your ajax code looks fine
try this
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y')
{
echo "alreadyLogged"; exit;
}
elseif ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
}

I think it is the php problem,it occur an error and return the error message. if ajax_login.php does not return "yes" or "no" it will show the second message, whatever it returns.

Just need modify your PHP. try this :
//Log In credentials
// check if post if (isset($_POST)) {
// must initially to use check if on loggin
session_start();
// set variable post
$username = $_POST['user_name'];
$password = $_POST['password']; // change if use sha1 or md5
$rand = $_POST['rand'];
// check query database
$query = mysql_query("SELECT * FROM Users WHERE username='$username' AND password='$password'");
$user = mysql_fetch_array($query);
$row = mysql_num_rows($query);
if ($row > 0) {
if ($user['LOGGED'] == 'Y') {
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate = mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
} elseif ($user['LOGGED'] == 'N') { // you can use 'else'
echo "alreadyLogged";
exit;
}
} else {
// invalid value password and username
echo "no";
exit;
} }

Related

PHP authentication dialog keeps repeating

I'm using PHP and want to authenticate a user against an entry in a MySQL database. All pages use HTTPS.
The problem is when I enter the correct username and password, the authorize dialog box disappears then reappears with the username and password blank.
Does anybody know how to fix it?
Snippets of code:
<?php
session_start();
if($_SERVER["HTTPS"] != "on")
{
header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER ["REQUEST_URI"]);
exit();
}
require_once("../php-files/cookies.php");
require_once("../php-files/db_connect.php");
/* If user tries to bypass logging in then we need to redirect back
* to main page. First though, we need to get whether we're localhost or
* live production.
*/
if($_SESSION["atHome"] == true)
{
require_once("/Calendar/Month.php");
require_once("/Calendar/Month/Weekdays.php");
}
else
{
require_once("../Calendar/Month.php");
require_once("../Calendar/Month/Weekdays.php");
}
include("../php-files/create-calendar.php");
include("../php-files/put-footer.php");
include("../php-files/timestamp.php");
//if cookie not set redirect back to home page
// prevents people from getting this page by using /php-files/new_event.php
// unless they have a cookie set
if(!isset($_COOKIE['www_broken_com']))
{
if($_SESSION["atHome"] == true)
header("Location: https://localhost");
else
header("Location: https://www.broken.com");
}
$theCookie = $_COOKIE['www_broken_com'];
$theCookie = explode(";",$theCookie);
//check to see if an Admin is going to enter a new event
//if so ask if they want to enter or to approve events submitted
function authenticate_user()
{
header('WWW-Authenticate: Basic Realm="New"');
header("HTTP/1.0 401 Unauthorized");
return(FALSE);
}
$authenticate = TRUE;
$authorized = FALSE;
$authorizedName = "";
$privleges = "";
//Compare the email address of the person currently accessing and see if
//he's in the admin database. If so then he as admin privleges.
$db_conn = new db_stuff();
$db = $db_conn->connect();
$query = "SELECT * FROM admin WHERE email = '$theCookie[5]'";
if(!$result = $db->query($query)) exit("Could not select for new event");
if($result && $result->num_rows != 0)
{
if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']))
$authenticate = authenticate_user();
if($authenticate == TRUE)
{
$userName = $_SERVER['PHP_AUTH_USER'];
$userPwd = $_SERVER['PHP_AUTH_PW'];
$query = "SELECT * FROM admin WHERE name = '$userName' AND pwd = PASSWORD('$userPwd')";
if(!$result = $db->query($query))
echo "<br />Could not select for authentication";
if($result && $result->num_rows != 0)
{
while($admin = $result->fetch_array())
{
$authorizedName = $admin[2] . " " . $admin[1];
}
$authorized = TRUE;
$privleges = ", you have administrator privleges.";
$_SESSION['authorizedName'] = $authorizedName;
}
}
else
{
exit("In FALSE");
$authorized = FALSE;
$_SERVER['PHP_AUTH_USER'] = "No one";
}
}
else
$privleges = " ";
After much digging......
run phpinfo() to see if: Server API = CGI/FastCGI (It should be the 4th line from the top)
If it is set, you can't do basic-authorization without a work-around.
Common workaround is to alter htaccess and add this line: RewriteRule .*-[E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
This worked for me.
See stackoverflow: Basic Authentication with PHP gives an endless loop for more info.

PHP MYSQLI Login Not Working

The Script Always Returns Failure(Regardless Of Correct/Incorrect User Information. Nothing Is Wrong with any other files. The Config File works and is just a starter of the sql connection and selects the database.
#include('../settings/config.php');
if (!#include('../settings/config.php')) {
die("<center>Login Failed</center>");
}
//======================================================================
// POST Check(Isset submit comes from html form)
//======================================================================
if(isset($_POST['submit'])) {
// Sanitize All POST Fields
$_POST = array_map('trim', $_POST);
$_POST = array_map('strip_tags',$_POST);
$login_form_user = $_POST['login_user'];
$login_form_pass = $_POST['login_pass'];
// Testing Only
echo("
<center>
Your Username is: $login_form_user!
<br>
Your Password is: $login_form_pass!
</center>
");
//======================================================================
// Input/Database Check
//======================================================================
$user_fetch = <<<LOGIN
SELECT `id` FROM `users`
WHERE `username`='$login_form_user'
AND `password`='$login_form_pass'
LIMIT 1
LOGIN;
$user_result = $sql_connection->query($user_fetch);
if(!$user_result) {
die("<center>Cannot Execute SQL Login Query</center>");
}
if ($sql_connection->num_rows == 1) {
echo("<center>User $login_form_user Exists</center>");
}
if($row = $user_result->fetch_assoc()) {
if(($row['username'] === $login_form_user) && ($row['password'] === $login_form_pass)) {
// Login Is Successful
echo("<center>Login Successful</center>");
} else {
echo("<center>Login Failed</center>");
}
}
} else {
// No Direct File Access Allowed
unset($_POST);
die('No Direct File Access Allowed!');
}
?>
Change:
if(($row['username'] === $login_form_pass)...
To:
if(($row['username'] === $login_form_user)...
You have typo error in this line please change it
if(($row['username'] === $login_form_pass) && ($row['password'] === $login_form_pass))
$row['username'] === $login_form_user// you are comparing it with $login_form_pass

PHP same Session user login

I searched but I can't find solution for me.
I have login.php file which redirect user to another page in my case theme.php?id=".$row['log_name'].".
<?php
include ('conn.php');
//Uzivatelsky vstup
$log_meno = mysqli_real_escape_string ($Conn, $_POST['login_name']);
$cmp_heslo = sha1($_POST['login_password']);
$sql = "SELECT id, cmp_heslo, log_meno FROM firmy WHERE log_meno='$log_meno'";
$result = mysqli_query($Conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_assoc($result)) {
if ($cmp_heslo == $row[cmp_heslo])
{
session_start();
$_SESSION['logged'] = 'yes';
echo "<script language='javascript'>window.location='comp_page/theme.php?id=".$row['log_name']."';</script>";
}
else
{
echo "<script language='javascript'>window.location='bad_login.php';</script>";
}
}
} else {
echo "0 results";
}
mysqli_close($Conn);
?>
theme.php
<?php
session_start();
if($_SESSION['logged'] != 'yes' )
die("You have to sign in first!");
?>
In MySQL I have two users
kuki with pass kuki
cuki with pass cuki
My question is when I am signed in as kuki I have in address bar:
http://localhost/comp_page/theme.php?id=kuki
But I need when I rewrite in address bar kuki to cuki to change to access denied becuase now only address bar changed but page is same. I am new to PHP.
Aside from having this in your session
$_SESSION['logged'] = 'yes';
I suggest you need to add also something like this,
$_SESSION['id'] = $row['log_name'];
and in your theme.php
session_start();
if($_SESSION['logged'] != 'yes' ) {
die("You have to sign in first!");
} else {
if ($_SESSION['id'] == $_GET['id']) {
// do somthing
} else {
echo "Access Denied!";
}
}
having this URL
http://localhost/comp_page/theme.php?id=kuki
meaning you are sending data, the id to the server with the get method. This $_GET['id'] catch that data and will have a value either kuki or cuki from the URI theme.php?id=kuki or theme.php?id=cuki.
This condition if ($_SESSION['id'] == $_GET['id']) will determine if the value of id is the same with the user store in the session.

Strange Password_Hash Issue

So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>

how to set a session time for specific page

When you go to this page;
http://www.ctuchicago.com/registration/login.php
you will see the form that I made. I want to create a session if username and password is true than I wanna set a 20 minutes expire time for it. How can I do it ?
my check.php
$user = $_POST['user'];
$pass = $_POST['pass'];
$ruser = "a";
$rpass = "b";
if ($user == $ruser) {
$logn = "True";
} else {
$logn = "False";
}
if ($pass == $rpass) {
$logs = "True";
} else {
$logs = "False";
}
if ($logn == "False" && $logs == "False") {
echo '<script type="text/javascript">alert("The Username and The Password are both wrong ! Please check your information and try again.");history.go(-1);</script>';
} elseif ($logn == "True" && $logs == "False") {
echo '<script type="text/javascript">alert("The Username is True but something is wrong with the password you entered. Please check your information and try again.");history.go(-1);</script>';
} elseif ($logn == "False" && $logs == "True") {
echo '<script type="text/javascript">alert("The Password is True but something is wrong with the password you entered. Please check your information and try again.");history.go(-1);</script>';
} else {
$_SESSION['valid'] = "1";
echo '<script type="text/javascript">window.location = "http://www.ctuchicago.com/registration"</script>';
}
my index.php (this page I want to be login required.
if ($_SESSION['valid']) {
echo '<script type="text/javascript">window.location = "http://www.ctuchicago.com/registration/login.php"</script>';
} else { Code }
Thank You
According to http://prajapatinilesh.wordpress.com/2009/01/14/manually-set-php-session-timeout-php-session/
ini_set(’session.gc_maxlifetime’, 20*60);
Have you considered using a [client side] cookie that expires in 20 minutes ? then whenever the page is (re)loaded, check for the cookie, invalidate the session if the cookie is invalid/expired.
See How do I expire a session after 30 minutes
EDIT
Basically what you are doing is creating your own session timeout function. When you hit the page you look for a variable you set in $_SESSION lets call it $_SESSION['started']. If you don't find that variable then you create it and give the value of the current timestamp. What you do then is every time you load a new page, you compare the $_SESSION['started'] variable with the time now and if it exceeds 20 minutes then you expire log the user out or do whatever you need to do.

Categories