简体   繁体   中英

if is not session , redirect to login page

I am trying to code a simple script, I created a " ADMIN Panel " , so if the user is admin (admin=1) then he can pass and see the link/file If he is not (admin=0) then he should be redirected to login page , and if is not Session['username'] he should go back to login page , but it seems that i have a problem with this code, in user panel it works , but in admin panel it doesn't

<?php

include './includes/db.php';
session_start();




// ADMIN CHECk

$username = mysql_real_escape_string($_SESSION['username']);

$result = mysql_query("SELECT * FROM users WHERE username='$username' AND admin=1");

$count = mysql_num_rows($result);



if($count != 1) // make sure user is a admin

{
        session_start();

        session_destroy();

    header("location: login.php");

    die;

}



if(isset($_GET['act'])) 
{
    if($_GET['act'] == "logout") 
    {
        session_start();
        session_destroy();
        header("location: login.php");
    }
}


?>

Ok, first thing i see is that you don't declare the session first. Secondly, the mysql function is deprecated, mysqli will do what you need done. This fix should work for you. Also it would be easier to have a logout.php.

db.php

<?php

$db = new mysqli(host, user, pass, database);

?>

Then, in your page, you can run the queries like so:

<?php

session_start();
include './includes/db.php';

//check that the session exists
if(!isset($_SESSION['username'])
{
  //the session does not exist, redirect
  header("location: login.php");
}

// ADMIN CHECk
$username = $db->real_escape_string($_SESSION['username']);

$result = $db->query("SELECT * FROM users WHERE username='$username' AND admin='1'");

$count = $result->num_rows;



if($count != 1) // make sure user is a admin

{
    header("location: login.php");
}

?>

Then in logout.php, you should remember to actually unset the session variables

<?php
 session_start();
 //unset session variables
 unset($_SESSION['username']);
 session_destroy();
 header("location: login.php");
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM