I have defined a function to check user credentials and would like it to return true if the auth passed and false if it failed. my function is defined as follows:
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
return $logged_in;
}
the problem I am running into is this, when I call the function and try to use what should be the returned value I get an error that the variable is not defined.
_userLogin($username, $password);
if ($logged_in == True){
'do something';
} else {
'do something else'
}
what am I doing wrong?
You are trying to use the variable $logged_in that is defined in function _userLogin outside the block. Assign the return value that is returned by the function like,
$logged_in = _userLogin($username, $password)
if ($logged_in == True){
'do something';
} else {
'do something else'
}
Also you will always receive TRUE because you are accessing variables $salt, $password outside the if block where they are being retrieved thus the fields not being assigned properly.
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in = false;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
$dbpass = '';
$salt = '';
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
}
}
return $logged_in;
}
PLEASE NOTE: I did not perform any logic checks other than fix your syntax
Replace your branching (where you use the function) with the simpler:
if( _userLogin($username, $password) ){
//success
}else{
//failure
}
Related
I am working on php and mysql code on making access to different pages based on the role of the user, through one Login Page.
Its working good for 'admin' page ..
but not able to login with 'normal type'
Little Help is really appreciated, Thank You
Here is my Code
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query) ;
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result) ;
if ($count == 1) {
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
}
elseif($row['user_type'] = 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
}
?>
Move your session code after if condition and then redirect. Also is there any specific reason to store password in session. == missing
Use proper filters for inputs.
if ($count == 1) {
if(!empty($row['user_type'])) {
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
//$_SESSION['password'] = $row['user_pass'];
}
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
}
elseif($row['user_type'] == 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
The logic test for the normal user was using a single = sign which sets a value rather than tests for equality - it needs to be ==
Also, I think the WRONG USERNAME OR PASSWORD wa at the wrong level - it needs to be the else to the record count
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result);
if ($count == 1) {
if($row['user_type'] == 'admin') {
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
/* require `==` here */
} elseif( $row['user_type'] == 'normal' ) {
header('Location: index.php');
} else {
die('unknown/unhandled user level');
}
/* changed location of this by one level */
} else {
echo "WRONG USERNAME OR PASSWORD";
}
}
?>
This is function for login.
It presumes password come from user with sha512 encryption (see js libs like https://github.com/emn178/js-sha512) - it's good for non-encrypted connections.
It uses salt, and have some protection from brute force, CSRF, XSS and SQL-injection.
static public function db_login($email, $p)
{
if ($stmt = Site::$db->prepare(
"SELECT id, password, salt, name
FROM user
JOIN contact ON contact_id = id
WHERE email = ?
LIMIT 1")
) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $db_password, $salt, $name);
$stmt->fetch();
// hash the password with the unique salt
$p = hash('sha512', $p . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (self::checkBrute($user_id) == true) {
// Account is locked
$res['code'] = 0;
$res['reason'] = 'trylimit';
$res['message'] = 'You try too many times. Come back on 30 minutes';
return $res;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $p) {
// Password is correct!
// Get the user-agent string of the user.
// CSRF
$user_browser = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_SPECIAL_CHARS);
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
Login::sec_session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = htmlspecialchars($email);
$_SESSION['name'] = htmlspecialchars($name);
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['login_string'] = hash('sha512', $p . $user_browser);
session_write_close();
// Login successful
$res['isLogined'] = 1;
$res['code'] = 1;
$res['name'] = $name;
$res['id'] = $user_id;
return $res;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
Site::$db->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')");
$res['code'] = 0;
$res['reason'] = 'pass';
$res['message'] = 'Wrong password';
return $res;
}
}
} else {
// No user exists.
$res['code'] = 0;
$res['reason'] = 'user';
$res['message'] = 'We have no such email';
return $res;
}
}
$res['code'] = 0;
$res['reason'] = 'SQL-error';
return $res;
}
ok I have a user login that uses email address and password when they login I want to pull there session data
like username and anything else from there record
I use this
<?php
if(isset($_SESSION['email'])) {
echo $_SESSION['email'];
}
?>
it works and pulls there email address but how do I get there username? I tried changing email to username and nothing shows
my login setup
/* login functions */
function login_user($email, $password, $remember)
{
$sql = "SELECT user_pwd, uid FROM users WHERE user_email = '" . escape($email) . "' AND active = 1";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['user_pwd'];
if (password_verify($password, $db_password)) {
if ($remember == "on") {
setcookie("email", $email, time() + 86400,'/');
}
$_SESSION['email'] = $email;
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
/* User Logged in Function */
function logged_in(){
if (isset($_SESSION['email']) || isset($_COOKIE['email'])) {
return true;
} else {
return false;
}
}
You need to make small changes in login_user() function.
function login_user($email, $password, $remember)
{
$sql = "SELECT user_pwd, uid, username FROM users WHERE user_email = '" . escape($email) . "' AND active = 1";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['user_pwd'];
if (password_verify($password, $db_password)) {
if ($remember == "on") {
setcookie("email", $email, time() + 86400,'/');
}
$_SESSION['email'] = $email;
$_SESSION['username'] = $row['username'];
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
Now you can use below code to get username in session. But make sure you must have username field in users table.
if(isset($_SESSION['username'])) {
echo $_SESSION['username'];
}
I have problem with get data from database.
This is my function:
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
var_dump(mysql_result($result));
if(mysql_result($result)>0){
//$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
else{
print_r('chuj');
}
}
and this is my function call:
$uid = $_SESSION['uid'];
$user = new User();
$register = $user->get_fullname($uid);
What is wrong with my code?
Full class in file Functions.php:
include_once 'config.php';
class User
{
//Połączenie z bazą danych
public function __construct()
{
$db = new DB_Class();
}
//Rejestracja
public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}
//Logowanie
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
var_dump($_SESSION);
return TRUE;
}
else
{
return FALSE;
}
}
//Pobieranie imienia
public function get_fullname($uid)
{
$result = mysql_query("SELECT * FROM users WHERE uid ='".$uid."'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if($no_rows>0){
$user_data = mysql_fetch_array($result);
//echo $user_data['name'];
return $user_data['name'];
}
else{
print_r('chuj');
return FALSE;
}
}
//Sesja
public function get_session()
{
return $_SESSION['login'];
}
//Wylogowanie
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
Fatal error: Call to undefined method User->get_fullname()
Rizier123's comment is correct, but not the cause of your problem.
I tried to reproduce the error but failed. That means that probably you're using an old version somewhere. If you're using FTP or the like, are you sure you uploaded the User class since you added the function?
Also, make sure that the most recent User class is included in the file where you're using it.
I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.
I have the PHP code as below:
<?php
if(isset($_POST["tbn_submit"])){
$userName = $_POST["text_username"];
$pass = $_POST["text_password"];
//$sql = "SELECT * FROM tbluser WHERE username='".$userName."' AND password='".$pass."'";
$sql = "SELECT * FROM tbluser";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)>0){
while($row= mysql_fetch_array($res)){
$username=$row['username'];
$userpas = $row['password'];
$user_id=$row['userId'];
$user_role=$row['possition'];
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if($userName == $username && $pass == $userpas){
if($user_role=="Admin"){
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}else{
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else if($userName == $username && $pass != $userpas){
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
else if($userName != $username && $pass != $userpas){
//In this point I got insert multi time so I want it insert only 1 time to database
$query = "INSERT INTO tbluser(userId,username,password,possition,user_status) VALUES('','".$userName."','".$pass."','',1)";
$result = mysql_query($query) or die(mysql_error());
$id = mysql_insert_id();
if($result){
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
}
}else {
echo "re";
}
}
?>
This is my login page submission. When the user inputs their username and password, if the username and password are already in the database it will go to test some case like in code, but if the username is in the database but the password does not match it should display wrong password..
If the username and password don't exist in the database, the program should create username and password and go to other page. I have an error with this last case - I have inserted a lot of records in the database with the same data. I know it's because I wrote these entries in a while loop in my code but I don't know any other way of doing this. How can I populate my database with individual records and not write duplicate entries in my while loop?
All your logic is wrong:
there's no need to retrieve ALL the users to check if the user exists,
tbluser should restrict username to be UNIQUE to avoid duplicated entries,
passwords should be hashed,
the INSERT query uses unescaped variables,
inserting non matching user names will lead to have typos stored at the db,
mysql_* family of functions are deprecated
Using PDO
Login user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
$username = $res['username'];
$password = $res['password'];
$user_id = $res['userId'];
$user_role = $res['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
Register user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$check = $_POST["passcheck"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$statement = $dbh->prepare("INSERT INTO tbluser (userId, username, password, position, user_status) VALUES ('', :user, :pass, '' , 1)");
$statement->bindParam(':user',$user);
$statement->bindParam(':pass',$pass);
$statement->execute();
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}
Using mysql_query (deprecated)
To validate any user:
<?php
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* This line had the right idea!
*/
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
$username = $row['username'];
$password = $row['password'];
$user_id = $row['userId'];
$user_role = $row['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
To register some user:
<?php
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* Ask the user to type its password twice
*/
$check = $_POST["passcheck"];
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
if (mysql_num_rows($res) > 0) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$query = "INSERT INTO tbluser (userId, username, password, possition, user_status) VALUES ('','".mysql_real_escape_string($user)."','".mysql_real_escape_string($pass)."','',1)";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}