Add session variables for multiple users - php

I have a login page which directs to a process_login page which in turn directs the user to the appropriate page(i.e. i have a SQL table with 3 users - admin, student, instructor)
The code below achieves that but i am having difficulty when i try to add session variables. I have commented out the code i was trying when adding the session variables.
What would be the best way to add session variables to this?
process_login
<?php
//session_start();
include('connect.php');
$name =$_POST['userlogin'];
$pass = $_POST['userpw'];
//$_SESSION['currentuser'] = $name;
$loginsql = "SELECT * FROM VLE_users WHERE name = '$name' AND passw = '$pass' ";
$result = $conn -> query ($loginsql);
if(!$result) {
echo $conn ->error;
}
//$num = $result -> num_rows;
//if($num>0){
while ($row = $result->fetch_assoc()){
//$userid =$row ['id'];
//$S_SESSION['userid'] = $userid;
if($row['type'] == 3){
header('Location:index2.php');
}elseif($row['type'] == 2){
header('Location: studentpage.php');
}elseif($row['type']==1){
header('Location:admin_dash.php');
}else{
header('Location:index.php');
}
}
?>

$_SESSION["currentuser"] = $name;
Should work just fine
$S_SESSION['userid'] = $userid;
Should be :
$_SESSION['userid'] = $userid;
did you make a typo there or? And exactly what is the trouble you are experiencing? what doesn't work ?

Related

How to pass id in url when user login with his detail

hey every one i have on query plse help me
i want if user login with his login detail his id should be pass and should be visible in link bar ?id=000 like this.
i am trying lot but not able to resolve it plse help me guys...
<?php
include('db.php');
session_start();
if (isset($_POST['submit'])){
//$id= $_POST["id"];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$query = "SELECT * FROM register WHERE email='$email' and pwd='$pwd'";
$result = mysqli_query($connection, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
header("Location:Employee/dashboard.php"); //here if user successfully log in his user id should be also visible in url bar
}else{
$query = "SELECT * FROM art WHERE email='$email' and pwd='$pwd'";
$result = mysqli_query($connection, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
header("Location:Recruiter/dashboard.php");
}else{
echo "<script>alert('Incorrect user id and password')</script>";
}
}
}
?>
Below is the modification to your code that needs to be done. You will need to fetch id from the table, if the credentials are valid and append that id to the URL:
$query = "SELECT id FROM register WHERE email='$email' and pwd='$pwd'";
$result = mysqli_query($connection, $query) or die(mysql_error());
$rows = mysqli_fetch_array($result);
if(isset($rows['id']) && $rows['id'] > 0){
$_SESSION['email'] = $email;
header("Location:Employee/dashboard.php?id=" . $rows['id']);
You don't have to send user_id from POST or GET, Set user_id in session at login time. and fetch it from session where you need it..this is the best solution..
OR
You can send it in your form as a hidden input
<input type="hidden" name="id" value="{$id}">
You probably get the answer from previous answers but I am adding this answer as the best practices to use the session to this kind of activity.
begins the session, you need to say this at the top of a page or before you call session code session_start();
put a user id in the session to track who is logged in $_SESSION['user'] = $user_id; . Then for Check if someone is logged in or not.
if (isset($_SESSION['user'])) {
// if logged in
} else {
// if not logged in
}
Find the logged in user ID $_SESSION['user'].
to redirect use this function:
function redirect($url){
if (headers_sent()){
die('<script type="text/javascript">window.location.href=\'' . $url . '\';</script>');
}else{
header('Location: ' . $url);
die();
}
}
save user id in $_SESSION['id'] = $_POST['user_id']; and change your code like this:
if($rows==1){
$_SESSION['email'] = $email;
redirect(SITE_URL.'Employee/dashboard.php?id='.$_SESSION['id']); //here if user successfully log in his user id should be also visible in url bar
}
after user logged in check url everywhere you want like blow and if id not exist redirect again:
if(!isset($_GET['id'])){
$url = CURRENT_URL;
$url .= '?id='.$_SESSION['id']; //or $url .= '&id='.$_SESSION['id']; if some variables set befor
redirect($url);
}
Why did you want to display id in URL ?After login, you can access it from the user session. If you still want then here is the code.
<pre>
$query = "SELECT id FROM art WHERE email='$email' and pwd='$pwd'";
$result = mysqli_query($connection, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$data = mysql_fetch_assoc($result);
$_SESSION['email'] = $email;
header("Location:Recruiter/dashboard.php?id=".$data['id']);
}else{
echo "<script>alert('Incorrect user id and password')</script>";
}
}
}
</pre>

Session Variables are lost after redirecting using header()

I have got index.php file that takes username and password from users, then it redirects to process_login.php that compares these credentials with SQL database to authorize the users. Now if the user is authorized, I want to get all the data about this user and want to use in other PHP files. I am using sessions to do so, but somehow they are not working.
I know they are so many similar questions, but none of them worked.
Here is my process_login.php code
<?php
session_start();
require_once('connectdatabase.php');
if(isset($_POST) && !empty($_POST)) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = mysqli_query($connection, $sql);
echo $count = mysqli_num_rows($result);
if($count == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['first_name'] = $row["FIRST_NAME"];
$_SESSION['last_name'] = $row["LAST_NAME"];
$_SESSION['email'] = $row["EMAIL"];
$_SESSION['username']=$username;
header('Location: ../../src/welcome.php');
exit();
}
else {
header('Location: ../../src/index.php');
}
}
?>
Now I want those variables on welcome.php file.
And this is my welcome.php code
<?php
session_start();
$fist_name = $_SESSION['first_name'];
echo "<script>console.log('$first_name');</script>";
?>
It's because you are using $fist_name rather than $first_name. And edit your echo part
<?php
session_start();
$fist_name = $_SESSION['first_name'];
echo "<script>console.log('$first_name');</script>";
?>
To
<?php
session_start();
$first_name = $_SESSION['first_name'];
echo $first_name;
?>
I wanted to comment but I can't so here is my suggestion for you.
When something like your issue happens to me I tend to echo the $_SESSION all of them to see if they're actually set or not.
Below is a small PHP script which does the same but I'm using PDO as the DB API.
if (isset($_REQUEST["pWord"])){
$inmPword = md5($_REQUEST["pWord"]);
$loginData = "SELECT * FROM userlogin WHERE pWord = :pWord";
$loginDataQuery = $dbConnect -> prepare($loginData);
$loginDataQuery -> bindParam(':pWord', $inmPword);
$loginDataQuery -> execute();
if ($row = $loginDataQuery -> fetch(PDO::FETCH_ASSOC)){
//Time to set the session
$_SESSION["uId"] = $row["uId"];
$_SESSION["uRole"] = $row["uRole"];
$_SESSION["fName"] = $row["fName"];
$_SESSION["lName"] = $row["lName"];
echo "3";
}else{
echo "4";
}
}
I think it's better not do the row count and echo it. Something like this might help.
$sql = "SELECT * FROM users WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = mysqli_query($connection, $sql);
if($row = mysqli_fetch_assoc($result)) {
$_SESSION['first_name'] = $row["FIRST_NAME"];
$_SESSION['last_name'] = $row["LAST_NAME"];
$_SESSION['email'] = $row["EMAIL"];
$_SESSION['username']=$username;
header('Location: ../../src/welcome.php');
exit();
}

Changing database field when user logs into account

I'm trying to update a database table to change a field when a user logs in. When the user inputs his/her correct information, a query runs to change the field from 0 to 1. However, this does not happen. I'm assuming that my query statement is wrong. Can anyone explain to me what I did wrong with the statement and what I should do to fix it?
<?php
session_start();
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$p_num = $_POST["username"];
$pwd = $_POST["password"];
$query = "SELECT * FROM $user_table";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$user_id = "{$row['user_id']}";
$user_name = "{$row['user_name']}";
$password = "{$row['password']}";
$image = "{$row['image']}";
$email = "{$row['email']}";
$program = "{$row['program']}";
$role = "{$row['role']}";
$logged_in = "{$row['logged_in']}";
if(($user_id == $p_num) && ($pwd == $password)){
$_SESSION["id"] = $user_id;
$_SESSION["user"] = $user_name;
$_SESSION["program"] = $program;
$_SESSION["pass"] = $password;
$_SESSION["image"] = $image;
$_SESSION["email"] = $email;
$_SESSION["role"] = $role;
$_SESSION["logged in"] = $logged_in;
mysqli_query($connect, "UPDATE '{$user_table}' SET logged_in = 1 WHERE user_id = '{$p_num}'");
header("Location: ../pages/instructor.php");
}
else{
header("Refresh: 1; URL=../index.php");
}
}
}
?>
I actually figured this out myself. I was simply checking for the wrong values in the sql statement.

This webpage has a redirect loop PHP issue?

I am using the following codes in my login.php and index.php files.
I get the This webpage has a redirect loop error in the browser.
I know the issue is caused by the logic in the login.php file by the following code:
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: http://$storeShop.mysite.com/index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
specifically this line: header("location: http://$storeShop.mysite.com/index.php");
I just do not know how I can fix this issue!
LOGIN.PHP
<?php
session_start();
ob_start();
if (isset($_SESSION["manager"])) {
/*
IF THE USER IS LOGGED IN THE CODE BELOW SENDS THEM TO THEIR OWN SUBDOMAIN NAME
WHICH IS STORED IN $_SESSION["storeShop"].
CHANGE "REST_OF_URL" TO THE VALID DOMAIN IN THE HEADER FUNCTION.
BUT DON'T REMOVE THE . (DOT)
*/
header("Location: http://$_SESSION[storeShop].mysite.com/index.php");
exit();
// END OF EDIT.
}
?>
<?php
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"]; // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
$storenameTable = $_REQUEST['storeShop'];
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.id, members.email, members.password, members.randKey, members.storeShop, storename.email, storename.password, storename.randKey, storename.storeShop
FROM members
INNER JOIN storename ON members.randKey = storename.randKey
WHERE members.email = '$manager'
AND members.password = '$password'
";
$result = mysqli_query($db_conx,"SELECT storeShop FROM members WHERE email='$manager' AND password='$password'");
while($row = mysqli_fetch_array($result))
{
$email = $row["email"];
$password = $row["password"];
$storeShop = $row["storeShop"];
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['storeShop'] = $storeShop;
}
// query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: http://$storeShop.mysite.com/index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
INDEX.PHP
<?php
session_start();
ob_start();
if (!isset($_SESSION["manager"])) {
header("location: login");
exit();
}
/*
THE CODE BELOW COMPARES THE SUBDOMAIN TO THE USER'S STORESHOP SESSION
IF THEY DON'T MATCH IT REDIRECTS THEM TO THEIR SUBDOMAIN.
CHANGE "REST_OF_URL" TO THE VALID DOMAIN IN THE HEADER FUNCTION.
BUT DON'T REMOVE THE . (DOT)
*/
else {
$url = $_SERVER["HTTP_HOST"];
$user_subdomain = explode(".", $url);
if($_SESSION["storeShop"] != $user_subdomain[0]) {
header("Location: http://$_SESSION[storeShop].mysite.com/index.php");
}
}
ob_end_flush();
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = $_POST["email"]; // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
$storenameTable = $_REQUEST['storeShop'];
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.id, members.email, members.password, members.randKey, members.storeShop, storename.email, storename.password, storename.randKey, storename.storeShop
FROM members
INNER JOIN storename ON members.randKey = storename.randKey
WHERE members.email = '$manager'
AND members.password = '$password'
"; // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$result = mysqli_query($db_conx,"SELECT storeShop FROM members WHERE email='$manager' AND password='$password'");
while($row = mysqli_fetch_array($result))
{
$email = $row["email"];
$password = $row["password"];
$storeShop = $row["storeShop"];
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['storeShop'] = $storeShop;
}
?>
could someone please point me in the right direction?
Thanks in advance.
You have started another session in index.php using session_start()
Remove the session_start() from index.php page and confirm if it is working fine
You're redirecting users to a different subdomain, and probably losing all your session data in the process.
Before you call session_start(), make sure your cookies are valid for the whole domain, i.e.,:
session_set_cookie_params(0, '/', '.mysite.com');
session_start();
More information here
Edit: Some other things you should look into:
(1) After the user has been redirected to "login" (header("location: login");), which of your scripts will process the next request? (Did you mean login.php?)
(2) What does login.php do when it receives a GET request (without an active session)?

phpMyAdmin user levels

I found this tutorial to create a members only area on my webpage using phpMyAdmin. The only problem I have is I need to have different pages show for different user levels. Currently all my users are user level 0, I would like to create an admin user as user level 1. I believe the php file I need to change is the one below, it is my checkuser.php file. Any help or direction would be much appreciated! Thanks in advance.
<?
/* Check User Script */
session_start(); // Start Session
include 'db.php';
// Conver to simple variables
$username = $_POST['username'];
$password = $_POST['password'];
if((!$username) || (!$password)){
echo "";
include 'loginError.php';
exit();
}
// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
$$key = stripslashes( $val );
}
// Register some session variables!
session_register('first_name');
$_SESSION['first_name'] = $first_name;
session_register('last_name');
$_SESSION['last_name'] = $last_name;
session_register('email_address');
$_SESSION['email_address'] = $email_address;
session_register('special_user');
$_SESSION['user_level'] = $user_level;
mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");
header("Location: /restricted/index.php");
}
} else {
echo "";
include 'loginError.php';
}
?>
Simple if
session_start();
if($_SESSION['user_level']==0){
header('location: no-access.php');
}
This will redirect user with level zero to no-access page. Put this top of page you want to restrict.

Categories