I can't get userid from session? - php

some help if you wish please for beginner user
will you please show me where is my code problem ?
i want to get user id from $_SESSION['userid']
but it's not working
i success to get username but not the id
i include session_start(); on each page to want to use it
but it's not showing the user id
only username working
here are my code
<?php
include("conn.php");
// variable declaration
$userid = "";
$username = "";
$email = "";
$errors = array();
$_SESSION['success'] = "";
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
unset($_SESSION['username']);
unset($_SESSION['userid']);
unset($_SESSION['user_type']);
header("location: ../login.php");
}
// return user array from their id
function getUserById($id){
global $conn;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// LOGIN USER
function login(){
global $conn, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1) { // user found
// Storing username in session variable
session_start();
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
$userid=$row['id'];
$username=$row['username'];
$user_type=$row['user_type'];
$_SESSION['username'] = $username;
$_SESSION['userid'] = $userid; // <-this variable should now exist
$_SESSION['user_type'] = $user_type;
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/home.php');
}else{
if ($logged_in_user['user_type'] == 'superuser') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: superuser/home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
} }else {
array_push($errors, "Wrong username/password combination");
}
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
function isSuperuser()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'superuser' ) {
return true;
}else{
return false;
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
// escape string
function e($val){
global $conn;
return mysqli_real_escape_string($conn, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
?>

As far as i can tell, your script would run.
Though please note that when using with sessions and $_SESSION globals, you have to initialise it first by adding session_start(); at the top of your page.
You should also dig into using PDO rather than mysqli or mysql.
I know this looks complicated, but it's the safest way to handle database queries.
Also don't use md5, use password_hash();
I also recommend adding var_dump($row); in this if statement, to see what data you are working with:
if (mysqli_num_rows($results) == 1) { // user found

Related

How to echo from database in session?

I have problem with PHP $_SESSION.
I see only "username" in index page after successfull login/register.
When I change $_SESSION['username'] to $_SESSION['password'] is also displayed.
I need to display "points" value, which is not defined by user during login/register (5 points is auto added to user after register)
How to echo values from database, which are not inserted by users?
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Please write username");
}
if (empty($password)) {
array_push($errors, "Please write password");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "Logged in ";
header('location: index.php');
}else {
array_push($errors, "Something went wrong");
}
}
}```
Try with :
...
if (mysqli_num_rows($results) == 1) {
$row=mysqli_fetch_assoc($result);
//check the data you get from the BD
var_dump($row);die;
// you'll get an array with you data where you'll find the points
// then just assign it to a session
$_SESSION['user_points'] = $row['user_points']; // for example
$_SESSION['username'] = $username;
$_SESSION['success'] = "Logged in ";
header('location: index.php');
}
...

Password always wrong using password_verify with database

I'm using password_verify with database when I login it always say password incorrect and in my database I'm using char 255 for password.
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
$userrecord1 = mysqli_query($db, "SELECT * FROM users WHERE username='$_POST[username]' LIMIT 1");
if (count($userrecord1) == 1 ) {
$urow1 = mysqli_fetch_array($userrecord1);
$hash = $urow1["password"];
}
// attempt login if no errors on form
if (count($errors) == 0) {
$passuser = password_verify($password, $hash);
$query = "SELECT * FROM users WHERE (username='$username' OR email='$username') AND password='$passuser' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Welcome admin";
header('location: /admin/home');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Welcome user";
header('location: /home/index');
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
There's a few things I'd like to note,
Usage of the global keyword is not recommended - you should instead pass values as arguments to the function instead.
You are wide open to SQL injection - use a prepared statement
Once you have verified the password by password_verify(), the password is correct and the user has verified his login.
if (count($userrecord1) == 1 ) { doesn't make much sense, as you haven't fetched any records yet.
Your second select is moot (see point 3), and invalid as selecting from a hashed password will not yield the result.
Use exit; after header("Location: .."); calls
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
$stmt = $db->prepare("SELECT password, user_type FROM users WHERE username=? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($dbPassword, $userType);
if ($stmt->fetch() && password_verify($password, $dbPassword)) {
if ($userType == 'admin') {
$_SESSION['user'] = $username;
$_SESSION['success'] = "Welcome admin";
header('location: /admin/home');
exit;
} else {
$_SESSION['user'] = $username;
$_SESSION['success'] = "Welcome user";
header('location: /home/index');
exit;
}
} else {
$errors[] = "Wrong username/password combination";
}
}

PHP/MYSQL Get data from the database for each specific user assigned

I'm making project doctor appointment system and have 1 admin 3 normal users (doctors)assigned.
For each doctor, I want to only show to them the appointments specifically assigned to them to load on their dashboard. Appointment that was not assigned to them will not be listed on their dashboard.
Is it possible if I can insert a function when they log in? and get the data based from there ID? If so, how can I do it?
Below are my source code for admin and normal users.
<?php
session_start();
// connect to database
$db = mysqli_connect('localhost', 'root', '', 'appointments');
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
header("location: ../login.php");
}
// REGISTER USER
function register(){
global $db, $errors;
// receive all input values from the form
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created!!";
header('location: home.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
}
// return user array from their id
function getUserById($id){
global $db;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// LOGIN USER
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: dashboard.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: doctordashboard.php');
}
}else {
array_push($errors, "Invalid username or password");
}
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
?>
Any help would be appreciated. Thanks

PHP Error in validating SESSION variable

So I've made a login system here, it initiates a session, checks if the password is correct and then sets the session variables.
Here are a few things you might want to note:
It successfully logs in
There is no problem with the mysql connection
All files are places correctly in folders
There are no warnings or error messages
The MYSQL Table structure is correct and there are no errors in database
Note: all functions I'm about to define are in the same file 'functions.php'
Over here we have the session function
include_once("global_config.php");
include_once("db_connect.php");
function sec_session_start()
{
$session_name = 'sec_session_id';
$secure = SECURE;
$httponly = true;
if(ini_set('session.use_only_cookies', 1) === FALSE)
{
echo "Could not initiate a secure session";
exit;
}
$cookieparams = session_get_cookie_params();
session_set_cookie_params($cookieparams['lifetime'],$cookieparams['path'],$cookieparams['domain'],$secure,$httponly);
session_name($session_name);
session_start();
session_regenerate_id();
}
The global_config file define the mysql password, database, user and host and the db_connect file simply return the mysqli_connect to connect to the database.
And this over here is the login function
function login($user,$pass){
sec_session_start();
$link=linkit();
if(empty($user) || empty($pass) || !isset($user) || !isset($pass)){
echo "Error Code: 313, Please contact network administrator for more information";
exit;
}else{
$usercheck = "SELECT `id`,`username`,`password`,`salt` FROM `".LOGINTABLE."` WHERE `username`=? LIMIT 1";
if($stmt=$link->prepare($usercheck)){
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$username,$realpassword,$salt);
$stmt->fetch();
$stmt->close();
if(empty($realpassword)){
echo 'Unrecognized Username, Please enter a valid username';
exit;
}else{
if($realpassword===$pass){
$_SESSION['username'] = $user;
$_SESSION['user_id'] = $id;
$_SESSION['login_string'] = hash('sha512',$pass);
return true;
}else{
echo "Invalid Password!";
exit;
}
}
}
}
}
The linkit() method is the one defined in db_connect.php which returns mysqli_connect. Also note that the script successfully makes it to setting the Session variable which means that it does return true.
NOW THE PROBLEM is this, when I'm checking for logged in status
function check_login()
{
if(isset($_SESSION['user_id']) &&
isset($_SESSION['login_string']) && isset($_SESSION['username']))
{
$user_id = $_SESSION['user_id'];
$username = $_SESSIOOO['username'];
$login_string = $_SESSION['login_string'];
$pwd_check = "SELECT `password` FROM `".LOGINTABLE."` WHERE `user_id`=? LIMIT 1";
if($stmt = linkit()->prepare($pwd_check))
{
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->bind_result($realpassword);
$stmt->fetch();
$stmt->close();
$hashedpass = hash('sha512',$realpassword);
if($login_string==$hashedpass){
return true;
}else{
return false;
}
}else{
return true;
}
}else{
return false;
}
}
AND FINALLY, this is WHERE I process my login script. Also note that there are no errors in POST methods or anything else. They all work fine.
This is in a separate php file and NOT in the functions.php
<?php
include_once '../includes/functions.php';
if(empty($_POST['loginuser']) || !isset($_POST['loginuser']) || !isset($_POST['id']) || empty($_POST['id']) || !isset($_POST['password']) || empty($_POST['password']))
{
echo "Error Code: 412, Please contact network administrator for more information";
exit;
}else{
if($_POST['loginuser']==="true")
{
$user = $_POST['id'];
$pass = $_POST['password'];
if(login($user,$pass)==true)
{
echo "Logged In!";
}else
{
echo "Failed to login, check your username or password";
}
}
}
?>
Additional Information :
The response I get is "Logged In"
Session is successfully creaated
PROBLEM: When I check for the login status, it returns false despite of having the session variables set.
In check_login you are hashing the password and then compare the unhashed password
function check_login()
{
if(isset($_SESSION['user_id']) &&
isset($_SESSION['login_string']) && isset($_SESSION['username']))
{
$user_id = $_SESSION['user_id'];
$username = $_SESSIOOO['username'];
$login_string = $_SESSION['login_string'];
$pwd_check = "SELECT `password` FROM `".LOGINTABLE."` WHERE `user_id`=? LIMIT 1";
if($stmt = linkit()->prepare($pwd_check))
{
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->bind_result($realpassword);
$stmt->fetch();
$stmt->close();
$hashedpass = hash('sha512',$realpassword);
if($login_string==$hashedpass ){
return true;
}else{
return false;
}
}else{
return true;
}
}else{
return false;
}
}

PHP session problems

I have a login page and a 'member's area' page, the login code is here:
login.php
if ($account->is_logged_in())
{
$route->to(ACCOUNT_URL);
}
elseif (isset($_POST['username']))
{
if ($account->authenticates())
{
if ($account->log_in()) $route->to(ACCOUNT_URL);
}
else
{
$flash->set('error', 'The credentials you provided are incorrect.');
}
}
the functions (in a different file)
public function log_in ()
{
session_unset();
session_destroy();
if(session_start())
{
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $_POST['username'];
}
}
public function authenticates ()
{
$username = $_POST['username'];
$password = $_POST['password'];
if (ctype_alnum($username) && ctype_alnum($password))
{
$username = mysql_real_escape_string(filter_var($username, FILTER_SANITIZE_STRING));
$password = $this->encrypt(mysql_real_escape_string(filter_var($password, FILTER_SANITIZE_STRING)));
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Then my members area page:
if ($account->is_logged_in())
{
echo 'logged in';
}
elseif (!$account->is_logged_in())
{
echo 'not logged in';
echo session_id();
print_r($_SESSION['logged_in']);
}
login.php redirects me (meaning it authenticates my account), but when I get to members.php it echoes out 'not logged in' and that is all.
You'll need to call session_start() at the top of members.php (and any page that needs to access the $_SESSION.
// Must initiate the session to test if logged in.
session_start();
if ($account->is_logged_in())
{
echo 'logged in';
}
elseif (!$account->is_logged_in())
{
echo 'not logged in';
echo session_id();
print_r($_SESSION['logged_in']);
}
Do you have session_start() at the very beginning of all scripts which use sessions?

Categories