简体   繁体   中英

Sessions not working as expected PHP

I have multiple sites on same server with small changes. Issue is that when User login into A site and from url if he enter B site, he is allow to view content. How I can restrict user to view B site content.

Below if my authenication code

function validate_login($email , $password){
        global $_config;
        if(empty($email) or empty($password)){
            return false;
        }

        //Now perform validation here
        //$email = mysql_real_escape_string($email);
        //$password = mysql_real_escape_string($password);

        $query_obj = new execute_query();
        $where = 'email="'.$email.'" and password = md5("'.$password.'")';
        $result = $query_obj->select_query(array('*') , 'user' , $where);

        $user = array();

        if($result->num_rows > 0){

            $user = array();
            while($row = $result->fetch_assoc()) {
                $user = $row;
                $user['is_logged'] = true;
            }

            session_start();
            $_SESSION['user'] = $user;
            $url  = $_config['site_url'].'dashboard.php';
            //header('Location :'.$url);die;
            header("Location: ".$url);
        }
        return false;
    }

and on the top of every page I am checking session like.

<?php
session_start();
//echo "<pre>";print_r($_SESSION['user']);die;
if(!isset($_SESSION['user'])){ 
    $url  = $_config['site_url'].'login.php'; 
    //header('Location :'.$url);die;
    header("Location: ".$url);
} ?>

PS: One approach is to save unique_session_id in database and check if user belongs to current database or not. But I want some more generic and better solution.

Thanks

You could add an extra level to your session to store the 2 sites uniquely

<?php
    session_start();

    if(!isset($_SESSION['siteA']['user'])) { 
        $url  = $_config['site_url'].'login.php'; 
        header("Location: ".$url);
} 
?>

Know all you need to do is make sure code in siteA and siteB knows what the key value is for each site ie the siteA and siteB keys.

<?php
    session_start();
    $site = getSiteKeyFromConfig();

    if(!isset($_SESSION[$site]['user'])) { 
        $url  = $_config['site_url'].'login.php'; 
        header("Location: ".$url);
} 
?>

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