Jump to content

PHP Session


Custer

Recommended Posts

Okay, yesterday, I finished my login script and it takes users, if login is successful, to my members page, which I'm working on now. But I'm unsure as to how I should write a program to make sure the user is still logged in and even logged into that session from the login script. All I put in my login.php was SessionStart(); at the top of the code...

Link to comment
https://forums.phpfreaks.com/topic/60855-php-session/
Share on other sites

It's not SessionStart(), it's session_start().

 

Lets say the name of your session that you registered was "logged", this is how you would check if they are logged in.

 

<?php

session_start();

if (!isset($_SESSION['logged'])){
   echo "ERROR: You are not logged in.";
   exit;
}

//rest of code here, for if they are logged in

?>

 

Note:

You have to call session_start at the top of EVERY page that you want the session to carry over on.

Link to comment
https://forums.phpfreaks.com/topic/60855-php-session/#findComment-302802
Share on other sites

Granted his code isn't full proof. You want to first grab their user level $_SESSION['user_level'] and ensure it is greater than 0.  If so, then you grab their username on EVERY PAGE using $_SESSION['username'] and query the database.  From there you need to get all their information again and refresh their session variables in case someone tampered with them, including their user_level.  That is why it is best to put all this in a function, and then just include this function and call it at the top of every page.

Link to comment
https://forums.phpfreaks.com/topic/60855-php-session/#findComment-302807
Share on other sites

<?php

function checkLogin(){
    
    if (isset($_SESSION['username']) && isset($_SESSION['password'])){
        $query = "SELECT col FROM users WHERE username='{$_SESSION['username']}' AND password='{$_SESSION['password']}'";
        $result = mysql_query($query)or die(mysql_error());
    
        if (mysql_num_rows($result) < 1){
            echo "You'r not logged in!";
            exit;
        }
    }
}

?>

 

Now on the top of every page the user should be logged in for, just put this:

checkLogin();

Link to comment
https://forums.phpfreaks.com/topic/60855-php-session/#findComment-303644
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.