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'];
}
Related
I have a login page where user submit his password and email. he would redirect to index page and there will be display user FUll name.
include_once 'db.php';
if (isset($_POST['submit'])) {
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = $_POST['password'];
$sql = SELECT password, id FROM users WHERE email='" . escape($email) . "' AND active = 1;
$result = query($sql);
if (row_count($result) == 1){
$row = fetch_array($result);
$db_passpord = $row['password'];
$db_name = $row['full_name'];
if (md5($password) == $db_passpord) {
if ($remember == "on") {
setcookie('email', $email, time() + 86460);
}
$_SESSION['fullname'] = $db_name;
$_SESSION['email'] = $email;
return true;
}
else{
return false;
}
return true;
}
else{
return false;
}
}
$_SESSION['full_name']; It will display the username which is used. I want to display the Name of user name what is in database. There is a row in database named full_name I used $db_name to set row['full_name'].
I'm guessing that this isn't the actual code on the website since there are a number of errors present.
include_once 'db.php';
if (isset($_POST['submit']))
{
$email= mysql_real_escape_string(stripslashes($_POST['email']));
$password = $_POST['password'];
$sql = SELECT password, id FROM users WHERE email='".escape($email)."' AND active = 1;
$result = query($sql);
if(row_count($result) == 1)
{
$row = fetch_array($result);
$db_passpord = $row['password'];
$db_name = $row['full_name'];
if(md5($password) == $db_passpord)
{
if($remember == "on")
setcookie('email',$email, time() + 86460);
$_SESSION['fullname'] = $db_name;
$_SESSION['email'] = $email;
return true;
}
else
{
return false;
}
return true;
}
else
{
return false;
}
}
There are no quotes around the select statement, I'm guessing that the included DB.PHP file has with in it the functions "query" and "fetch_array", else they do not exist.
You are saying that the "echo $_SESSION['full_name']" does not display the full name, but your code is setting the full name to "$_SESSION['fullname']".
My login form is always saying that credentials are incorrect. The form was working before I changed it to use either username or email. Not sure whats wrong with my code.
/****************User login functions ********************/
function login_user($email, $username, $password, $remember) {
$sql = "SELECT password, id FROM users WHERE email = '".escape($email)." || username = ".escape($username)."' AND active = 1";
$result = query($sql);
if(row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['password'];
if(md5($password) === $db_password) {
if($remember == "on") {
setcookie('email', $email, time() + 86400);
}
$_SESSION['email'] = $email;
$_SESSION['username'] = $username;
return true;
} else {
return false;
}
return true;
} else {
return false;
}
} // end of function
/****************logged in function ********************/
function logged_in(){
if(isset($_SESSION['email']) || isset($_COOKIE['email'])){
return true;
} else {
return false;
}
}
Im not sure if anyone can help me sort this out
I should add 2 single quotes in your SELECT
function login_user($email, $username, $password, $remember) {
$sql = "SELECT password, id FROM users WHERE email = '".escape($email)."'
|| username = '".escape($username)."' AND active = 1";
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;
}
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
}
I wonder how to make every pages that need go through login page. If the person doesn't log in, it will redirect to login page.
I include a function
confirm_logged_in();
in every page but it keeps asking for the login even after I log in. Please tell me how to fix that It only needs to log in once but still the keeps people from entering a direct link manually.
I do have session_start(); in every page!
Here the code for login page
$username = "";
if (isset($_POST['submit'])) {
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)) {// Attempt Login
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login_admin($username, $password);
$found_client = attempt_login_client($username, $password);
if ($found_admin) {
$_SESSION["admin_id"] = $found_admin["admin_id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
}elseif($found_client){
$_SESSION["client_id"] = $found_client["client_id"];
$_SESSION["username"] = $found_client["username"];
redirect_to("client.php");
} else{// Failure
$_SESSION["message"] = "Username/password not found.";
}
}
}
Here the code for functions:
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
function logged_in() {
return isset($_SESSION['admin_id'] );
}
function confirm_logged_in() {
if (!logged_in()) {
redirect_to("login.php");
}
}
function find_admin_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE status='admin' ";
$query .= "AND username = '{$safe_username}' ";
$query .= "LIMIT 1";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
if($admin = mysqli_fetch_assoc($admin_set)) {
return $admin;
} else {
return null;
}
}
function find_client_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE status='client' ";
$query .= "AND username = '{$safe_username}' ";
$query .= "LIMIT 1";
$client_set = mysqli_query($connection, $query);
confirm_query($client_set);
if($client = mysqli_fetch_assoc($client_set)) {
return $client;
} else {
return null;
}
}
function attempt_login_admin($username, $password) {
$admin = find_admin_by_username($username);
if ($admin) {
// found admin, now check password
if (password_check($password, $admin["hashed_password"])) {
// password matches
return $admin;
} else {
// password does not match
return false;
}
} else {
// admin not found
return false;
}
}
$found_admin = attempt_login_admin($username, $password);
$found_client = attempt_login_client($username, $password);
if ($found_admin) {
$_SESSION["admin_id"] = $found_admin["admin_id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
}elseif($found_client){
$_SESSION["client_id"] = $found_client["client_id"];
$_SESSION["username"] = $found_client["username"];
redirect_to("client.php");
}
I don't understand if the functions attempt_login_admin() and attempt_login_client() return a bool or an array. If you fix that, It should work. You can return a bool in the associative array by assigning the return bool value to $found_admin['bool'] and verifying the bool in the if-block by if($found_admin['bool']) { ... }.