Strange Password_Hash Issue - php

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();
?>

Related

Get int from column by using email to identify row

I want to get and echo a users permission level.
I have a function where the users email is passed, the function then needs to get the users permission level and return it, so it can be echoed on another page.
I imagine the function will look though the database for the passed email, it then finds the users permission and returns with that.
In the 'User.class.php'
public static function permGetter($email)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email LIMIT 1');
$stmt->execute([':permission'=>$permission]);
$user = $stmt->fetchObject('User');
if($user !== false)
{
return $permission;
}
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
In the 'permRequest.php'
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email))
{
echo 'Permission ' + (int) $permission;
}
}
else
{
//I use level 5 as a debug so i can see when it fails
echo 'Permission 5';
}
}
?>
Database
Here's an example on what my database looks like.
Edit 1
Okay messing about, I think i got closer to the solution.
First, #Lawrence Cherone, thanks for pointing out my mistake in my execute.
Okay I have changed my code in
User.class.php
public static function permGetter($email, $permission)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email');
$stmt->execute([':email'=>$email]);
$row = $stmt->fetch(PDO::FETCH_NUM);
$permission = $row['permission'];
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
I have made small changes to
permRequest.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
$permission = '';
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email, $permission))
{
echo 'Permission ', $permission;
}
}
}
?>
But now i get an error. The error is this Notice: Undefined index: permission in /classes/User.class.php on line 56
So, I read up on it and it seemed like it should be emptied first, so I empty it in permRequest.php that's why I'm passing it too, but I still get this error after i emptied it?
However if i change
$row = $stmt->fetch(PDO::FETCH_NUM);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);
/* OR */
$row = $stmt->fetch(PDO::FETCH_BOTH);
I get no error but it simply says my email or password is incorrect, which it isn't I have double and triple checked it.
So I'm confused to which PDO::FETCH_ I should use. I have read this (Click here) and I would say that both ASSOC, BOTH and NUM would fit the purpose.
So why is one giving an error while the two other's simply fails the login?
Edit 2
Found the solution and i have written it as a Answer. Can't accept it for the next two days however.
I moved everything out of the User.class.php and moved it into permRequest.php. This solved my problem for some reason. So my code looks like this now
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
require_once("../includes/init.php");
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
if(Auth::getInstance()->login($email, $pass))
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sub = $row['permission'];
echo 'Permission ', $sub;
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
}
And I don't use the User.class.php for this function.
So my guess is something went wrong when returning $sub when it was in User.class.php

PHP $_SESSION returning incorrect value

Ok, so when I execute the initial function it works fine, the username gets stored in the database, however when I run the second function that appends the username to the text the user chooses to enter the IF statement returns 'no user' - when a user is defined...
If anyone knows how to fix this that would be great - I am currently learning PHP and mysql so I am sorry if any of this is incorrect
<?php
session_start()
// connect to the database
mysql_connect("localhost", "root", "");
mysql_select_db("ajaxchat");
// read the stage
$stage = $_POST['stage'];
// primary code
if($stage == 'initial') {
// check the username
$user = $_POST['user'];
$query = mysql_query("SELECT * FROM chat_active WHERE user='$user'");
if (mysql_num_rows($query) == 0) {
$time = time();
//
mysql_query("INSERT INTO chat_active VALUES ('$user', '$time')");
// set the session
$_SESSION['user'] = $user;
echo 'good';
}
else {
echo 'taken';
}
}
/////////////// PROBLEM FUNCTION ///////////////
================================================
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
// check for user_error
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
}
}
else {
echo 'error';
}
?>
This is the javascript:
<script type="text/javascript">
function chat_initialise() {
var user = document.getElementById("chat_user").value;
$.post("./chat.php", {stage:"initial", user:user}, function(data) {
if (data == "good") {
$('#initial').css('display', 'none');
$('#content').css('display', 'inline')
}
else {
alert("That username is taken! Please try another.");
}
});
}
function chat_send() {
var text = document.getElementById("chat_text").value;
$.post("./chat.php", {stage:"send", text:text}, function(data) {
document.getElementById("chat_text").value = '';
$('#window').text($('#window').text() + data);
// alert(data)
});
}
</script>
I fixed it - changed the POST function to take the current username then redefine it as a variable in the second function:
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
$user = $_POST['user'];
echo $user;
// check for user_error
if (isset($_SESSION['user'])) {
$_SESSION['user'] = $user;
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
var_dump($_SESSION);
}
}
Thanks for all your help guys!!

Codeigniter 2.2 failed create session

I use CI 2.2 to build a simple login system. But I get problem when I try to generate session. Of course I have properly set up libraries (database, session) and User_M. When I retrieve data from database (without session), that's work fine. This is my Controller code:
public function verify()
{
// Define variable
$user = $this->input->post('username');
$pass = $this->input->post('password');
// Check input data
if (!empty($user) AND !empty($pass))
{
// Check match data from db
$checks = $this->User_M->check_user($user, $pass);
if($checks->num_rows() == 1)
{
foreach ($checks->result() as $check)
{
$sess = array (
'username' => $check->username,
'logged_in' => TRUE
);
$rest = $this->session->set_userdata($sess);
if ($rest)
{
echo "working";
} else {
echo "not working";
}
}
} else {
echo "Not found";
}
} else {
echo "You've empty field";
}
}
Additional explain, I check the result with if ($rest)...bla..bla..bla, that's echoing Not Working. Please let me know where's my mistakes?
Thank in advance
I think the problem is with this statement
$rest = $this->session->set_userdata($sess);
the set_userdata() does not return anything, so according to your condition it will always execute the else part.
Try to change your condition like this
if (!empty($this->session->userdata("username"))){
echo "Working";
}else{
echo "Not Working";
}

Session not recognised on first attempt at logging in

Issue resolved - see: https://stackoverflow.com/a/14719452/1174295
--
I've come across a problem within (at least) Google Chrome and Safari.
Upon the first attempt at logging in, the user is not redirected. The session is created, but it is almost as if it is not detected, and takes the user back to the index page. Upon a second attempt, the correct redirect is issued and the user is taken to the correct page.
The script works fine in Firefox, and I have checked extensively to see if the correct data is being returned, which it is. I've searched and I've searched and I've searched, but unfortunately nothing of use has cropped up.
Access.php - User logging in
<?php
session_start();
ob_start();
include_once('db.class.php');
include_once('register.class.php');
include_once('login.class.php');
$db = null;
$reg = null;
$log = null;
$db = new Database();
$log = new Login($db, null, null, null, null, null, null);
if (isset($_SESSION['login'])) {
$log->redirectUser($_SESSION['login']);
}
include_once('includes/header.html');
?>
Some HTML...
<?php
if (isset($_POST['logsub'])) {
$db = new Database();
$log = new Login($db, $_POST['email'], $_POST['pass']);
$validation = &$log->validate();
if(empty($validation)) {
$log->redirectUser($_SESSION['login']);
} else {
echo "<div id='error'><div class='box-error'><p style='font-weight: bold'>The following errors occured...</p><ul>";
for ($i = 0; $i < count($validation); $i++) {
echo "<li>" . $log->getErrorMessage($validation[$i]) . "</li>";
}
echo "</ul></div></div>";
}
}
?>
Login.class.php - Login class
// Validate the credentials given
public function validateLogin() {
// Hash the plain text password
$this->hashedPass = $this->hashPassword();
try {
$query = $this->dbcon->prepare("SELECT Login_ID, Login_Email, Login_Password FROM Login WHERE Login_Email = :email AND Login_Password = :pass");
$query->bindParam(':email', $this->email, PDO::PARAM_STR);
$query->bindParam(':pass', $this->hashedPass, PDO::PARAM_STR);
$query->execute();
$fetch = $query->fetch(PDO::FETCH_NUM);
$this->loginid = $fetch[0];
// If a match is found, create a session storing the login_id for the user
if ($query->rowCount() == 1) {
$_SESSION['login'] = $this->loginid;
session_write_close();
} else {
return LOG_ERR_NO_MATCH;
}
} catch (PDOException $e) {
$this->dbcon->rollback();
echo "Error: " . $e->getMessage();
}
}
// Fetch the customer ID
private function getCustId() {
try {
$query = $this->dbcon->prepare("SELECT Customer.Cust_ID FROM Customer JOIN Login ON Customer.Login_ID = Login.Login_ID WHERE Customer.Login_ID = :loginid");
$query->bindParam(':loginid', $this->loginid, PDO::PARAM_INT);
$query->execute();
$fetch = $query->fetch(PDO::FETCH_NUM);
return $fetch[0];
} catch (PDOException $e) {
$this->dbcon->rollback();
echo "Error: " . $e->getMessage();
}
}
// Check the registration progress - are they verified? paid?
// This function is used elsewhere hence the $sessionid argument
public function checkRegistration($sessionid) {
$this->loginid = $sessionid;
$this->custid = $this->getCustId();
try {
$queryVer = $this->dbcon->prepare("SELECT Cust_ID FROM Customer_Verify_Email WHERE Cust_ID = :custid");
$queryVer->bindParam(":custid", $this->custid, PDO::PARAM_INT);
$queryVer->execute();
$queryFee = $this->dbcon->prepare("SELECT Cust_ID FROM Initial_Fee_Payment WHERE Cust_ID = :custid");
$queryFee->bindParam(":custid", $this->custid, PDO::PARAM_INT);
$queryFee->execute();
// If a record exists in the verify table, return the value 1. This means the user has not yet verified their email.
if ($queryVer->rowCount() == 1) {
return 1;
} else {
// If a record does not exist in the payment table, no payment has been made. Return 2.
if ($queryFee->rowCount() == 0) {
return 2;
// Otherwise, email is verified and the payment has been made.
} else {
return 0;
}
}
} catch (PDOException $e) {
$this->dbcon->rollback();
echo "Error: " . $e->getMessage();
}
}
// Redirect the user accordingly
public function redirectUser($sessionid) {
$this->loginid = $sessionid;
$logNum = $this->checkRegistration($this->loginid);
if ($logNum == 0) {
header("Location: fbedder/details.php", true, 200);
exit();
} else if ($logNum == 1) {
header("Location: fbedder/verification.php", true, 200);
exit();
} else if ($logNum == 2) {
header("Location: fbedder/payment.php", true, 200);
exit();
}
}
Here's a link to the site: fbedder/ -> I have set-up a test account with the credentials -> email: test# / password: test123321
To reiterate, the problem exists only in Google Chrome and Safari (the Safari being on my iPhone) and lies purely within the logging in aspect. On the first attempt, the session will be ignored (it is created), and on the second attempt, the user will be redirected.
Any ideas? I've tried a multitude of possibilities...
-- Edit --
I know where the issue lies now.
When the redirect is called, it sends the user to the details.php page. However, this page contains the following snippet of code:
if (!isset($_SESSION['login'])) {
header("Location: fbedder/index.php");
}
Obviously what is happening, is that the session is not being detected / saved / "whatevered", and as a result is sending the user back to the index page. Is there are a way to ensure the $_SESSION is not effectively lost. I had read about this before posting here, and is why I inserted session_write_close(), but that doesn't seem to be doing the desired effect.
After diagnosing the problem being within the fact the $_SESSION variable was effectively being lost, I read up about the session_write_close() function and came across this comment:
My sessions were screwing up because I had 2 different session IDs going at once:
1 PHPSESSID cookie for domain.com
1 PHPSESSID cookie for www.domain.com
This fixed it:
//At the beginning of each page...
session_set_cookie_params (1800,"/","domain.com");
session_start();
Source: http://pt2.php.net/manual/en/function.session-write-close.php#84925
Setting the parameters resolved the issue.

PHP and AJAX Log in validation

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

Categories