Managing two different SESSION in PHP - php

I have a table for users in my MySQL database with a tinyint value (0 or 1) which I use to determinate the category of the user.
So, at my login.php, I get the value (stored as 'admin'):
$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
$isadmin = intval($row['admin']);
Then I assign the session:
if (password_verify($pwd, $row['password']) && $count==1){
if($isadmin==1) {
$_SESSION['admin_session'] = $row['userid'];
header("location: adminpanel.php");
} else {
$_SESSION['user_session'] = $row['userid'];
header("location: adminpanel.php");
}
}
And when it comes to check the session, I do this:
if (isset($_SESSION['user_session'])){
header("location: adminpanel.php");
exit;
} else if(isset($_SESSION['admin_session'])){
header("location: adminpanel.php");
exit;
}
But... It's not working. The page doesn't load and it shows a browser error message saying there are too many redirections being made. How can I do this?
I know both sessions are heading to the same "adminpanel.php". What I'm trying to do is both can access but once they're logged, depending on its category (whether they're admin or not), they'll be able to do certain stuff.

I would suggest simplifying the process and just keeping a User in the session with a flag telling you if they are an admin or not.
$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
if (password_verify($pwd, $row['password'])){
$_SESSION['user'] = $row['userid'];
$_SESSION['isadmin'] = $row['admin'] == 1 ? true : false;
}
And when it comes to check the session, I do this:
if (isset($_SESSION['isadmin']) && $_SESSION['isadmin']){
header("location: adminpanel.php");
exit;
} else
// NOTE you had this redirecting exactly as above to adminpanel
header("location: userpanel.php");
exit;
}

Try to add ob_start(); on the top of your php script. I think it's because of your using header function many times.

Related

How to non-verify mobile number user redirect to verification page

If user is logged in then if his mobile number is verified then he will allow to move index.php else he will move to mobileverify.php. So i write a function and call this function in index page if unverified user tries to move in index.php function will redirect him mobileverify.php but function is not working please see the code below and tell me where i am wrong
function mobile_verify(){
if(isset($_SESSION['user_id'])){
$login = $_SESSION['user_id'];
$query =mysql_query("SELECT * FROM `users` WHERE `user_id`='$login'");
$row = mysql_num_rows($query);
$verify = $row['verify'];
if($verify === ""){
header('Location: mobileverify.php');
exit();
}
}
}
mysql_num_rows($query);
returns the number of rows in the result set not the values.
try
$row = mysql_fetch_array($result);
you are basically fetching the no of rows meeting your WHERE clause.
IT DOES NOT RETURN THE DATA ITSELF
you could use
$row = mysql_fetch_array($query);
and then check
$verify = $row['verify'];
if(!$verify){
header('Location: mobileverify.php');
}else{
header('Location: index.php');
}

PHP restriction error

I'm trying to restrict users from accessing a page if their rank isn't manager or admin. I made a variable called $rank which is the rank that is fetched from the user's table in my database. When I echo the rank on the page, the rank does equal to manager or admin but it redirects me to the index page because it somehow doesn't equal manager or admin. When I try using this code:
if(!isset($_SESSION['userID'])) {
header("Location: index.php");
} else if ($rank == "manager" OR $rank == "admin") {
} else {
header("Location: index.php");
}
it does work but I feel like that's the wrong way of doing it. This is the code that I'm using now and isn't working:
$tUsers_Select = "SELECT users.rank, ranks.rank_name FROM users LEFT JOIN ranks ON users.rank = ranks.rank_name WHERE user_id = ".$_SESSION['userID'];
$tUsers_Select_Query = mysqli_query($dbConnect, $tUsers_Select);
$fetch = mysqli_fetch_array($tUsers_Select_Query);
$rank = $fetch['rank'];
if(!isset($_SESSION['userID'])) {
header("Location: index.php");
} else if ($rank !== "manager" OR $rank !== "admin") {
header("Location: index.php");
}
Hopefully you understood. Please comment if you have any questions.
This is just a logic problem.
else if ($rank !== "manager" OR $rank !== "admin") {
If rank is manager, then it does not equal admin. If it is admin, then it does not equal manager. So no matter what happens you redirect to index.php.
Change OR to AND.
First of all, I want to ask you if the session_start() opened before you used the $_SESSION?
Then I suggest you to var_dump the $_SESSION['userID']) ,see if this virable is null.
Update:
I am not sure about your problem, and you can try this:
change the blow code :
if(!isset($_SESSION['userID'])) {
header("Location: index.php");
} else if ($rank !== "manager" OR $rank !== "admin") {
header("Location: index.php");
}
to:
if(isset($_SESSION['userID']) AND ($rank == 'manager' OR $rank == 'admin')) {
header("Location: index.php");
}
I think that can make your code simple.

Session lost after page redirect in php

When I use php header redirection all session variables are lost... Some people say that adding exit(); just after the header(""); will solve the problem but it doesn't seem to be the solution...
Can anyone please help?
Here is how I store variable into the session:
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['usr_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
if(empty($err)){
header("Location: myaccount.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
Redirection code:
//connect database
require_once 'dbc.php';
page_protect();
$authorID = $_SESSION['user_id'];
if ( !empty($_POST["answ_content"]) && $authorID != 0 ) {
//vaqciot html chveulebriv texad
$content = htmlentities($_POST["answ_content"],ENT_COMPAT,'UTF-8');
$dro = date('Y-m-d H:i:s');
$qID = $_POST["question_ID"];
$author = $_SESSION["user_name"];
$sql="INSERT INTO wp_comments (comment_ID, comment_post_ID, comment_author, comment_author_IP, comment_date, comment_content, user_id)
VALUES
(NULL, '$qID', '$author', '123.123.123.123', '$dro', '$content', '$authorID')";
$result = mysql_query($sql);
//pasuxebis raodenobis ertit gazrda
$increase = "UPDATE wp_posts SET comment_count = comment_count+1 WHERE ID = $qID";
mysql_query($increase);
//gadamisamarteba shekitxvis gverdze
$url = 'Location:http://example.com/site/answ/question.php?ID=' .$qID;
header($url);
} else {
echo 'error';
}
You need to put exit(); after your header redirection, otherwise you have just loaded two pages of content into 1 page.
Also make sure you have session_start(); at the top of all your scripts.
You aren't starting the session. In order to use session variables and have them carry across pages, you need to put
session_start();
at the top of each page before anything else.
I was trying to set the session id of my own using :
session_id('own_generated_session_id_string');
But as the documentation says, you have to use this before
session_start();
Using it after session_start(), clears the session parameters.
Simples! make sure the page you are coming from (e.g. www.example.com) redirects to a (eg.g www.example.com/redirect.php) notice www at the beginning. If you change that from page to page, then yes things get wonky.
These sessions does not always work as we expect sometimes. I had a similar problem with my website using sessions that get lost. I basically solved it by injecting the value I want to keep on the session into the hidden text field the first time the page loads. Then the second time I call the page(page submit) I simply read the value from the hidden text field and carry on with rest of my code.
That's more easier and cleaner than using sessions in this case!
exit; should be placed after header redirection or session_regenerate_id(true); can be used
You just need to check the file permission in /var/lib/php directory
give yje public permisssion to /var/lib/php/session directory.
and all done.
Include session_start(); in both the files before the session.
Note don't use session_destroy() in the redirected file.

$_SESSION difficulties

I am creating a login script that stores the value of a variable called $userid to $_SESSION["userid"] then redirects the user back to the main page (a side question is how to send them back where they were?).
However, when I get back to that page, I am echoing the session_id() and the value of $_SESSION["userid"] and only the session id shows up. It had occurred to me that maybe my redirect page needs to have at the top, but if this were true, then the session_id I'm echoing would change each time I end up on the page that is echoing it. Here is the script:
<?php
session_start();
include_once("db_include.php5");
doDB();
//check for required fields from the form
if ((empty($_POST['username']) && empty($_POST['email'])) || empty($_POST['password'])) {
header("Location: loginform.php5");
exit;
} else if($_POST["username"] && $_POST["password"]){
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE username='".$_POST["username"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit; }
} else if($_POST["email"] && $_POST["password"]) {
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE email='".$_POST["email"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit;}
} else {
//redirect back to login form
header("Location: loginform.php5");
exit;
}
mysqli_close($mysqli);
?>
You're doing this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
Where you should do this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $info["id"];
}
Make sure:
<?php
session_start();
Is at the top of each page.
Additionally, you can test by commenting out your redirects and echo'ing the value you're setting with to make sure you're retrieving/storing the correct value to begin with.
You need to call session_write_close() to store the session data changes.
Side answer: you can use the $SERVER["HTTP REFERER"] to redirect back, if it was filled by the browser

how to go back to login page if given wrong php GET credentials?

so im given 3 variables on my login page from an outside source, if one of those do not belong in the database I want it to just go to the normal login.php page. as of right now it stays on that page and does not change the url even though the vars are not in the db.
i give it localhost/john/login.php?uniqueID=BmWDLlkcyU&compID=2&tempID=22
, but tempID 22 does not exist so i want it to revert to login.php
$uniqueID = $_GET['uniqueID'];
$compid = $_GET['compID'];
$tempID = $_GET['tempID'];
$checkUnique = mysqli_query($conn, "SELECT unique_id from answers WHERE unique_id = '$uniqueID' and template_id = '$tempID'");
$checkComp = mysqli_query($conn, "SELECT company_id from t_list WHERE company_id = '$compid'");
if(!$checkUnique)
{
header("Location: login.php");
exit;
}
else if(!$checkComp)
{
header("Location: login.php");
exit;
}
do this way
$checkUniquerowcount=mysqli_num_rows($checkUnique);
$checkComprowcount=mysqli_num_rows($checkComp);
and check for
if( $checkUniquerowcount > 0 && $checkComprowcount >0 )
{
}
else
{
header("Location: login.php");
exit;
}

Categories