Jump to content

Understanding how $_Session works and my auth_session.php file


Fishcakes

Recommended Posts

Back with more noob questions :P

so I was following a page in setting up a login system and so far it works how I want except for one minor thing

So I want when a user is logged into the system to see Profile div instead of Login and Register and I do that in my index.php with the following

 <?php  if(isset($_SESSION['username'])){
	echo 
    	"<div class='profile'> 
  		    <a href='logout.php'>Logout</a>
  		    
  		    </div> 
  		    ";
    }
    else{
    	echo 
    	"<div class='loginregister'> 
  		    <a href='login.php'>Login</a>
  		    <a href='register.php'>Register</a>
  		    </div> 
  		    ";
    }
    ?>

So when a user logs in it hits the login.php which looks like this 

<?php
    require('dbconnect.php');

    session_start();
    // When form submitted, check and create user session.
    if (isset($_POST['username'])) {
        $username = stripslashes($_REQUEST['username']);    // removes backslashes
        $username = mysqli_real_escape_string($conn, $username);
        $password = stripslashes($_REQUEST['password']);
        $password = mysqli_real_escape_string($conn, $password);
        // Check user is exist in the database
        $query    = "SELECT * FROM `Users` WHERE User='$username'
                     AND password='" . md5($password) . "'";
        $result = mysqli_query($conn, $query) or die(mysql_error());
        $rows = mysqli_num_rows($result);
        if ($rows == 1) {
            $_SESSION['username'] = $username;
            // Redirect to user dashboard page
            header("Location: index.php");
        } else {
            echo "<div class='form'>
                  <h3>Incorrect Username/password.</h3><br/>
                  <p class='link'>Click here to <a href='login.php'>Login</a> again.</p>
                  </div>";
        }
    } else {

and it starts the session_start() function whilst also allocating $_SESSION['username'] = $username so in theory when index.php loads if SHOULD (?) hit the correct if statement in the index.php file now outputting the Profile div instead of the Login and Register div.

Except it doesn't.

However when I include the auth_session.php at the top of my index.php file like (currently uncommented to test)

//<?php //include auth_session.php file on all user panel pages 
//include("auth_session.php");
//?>

with the Auth_session file looking like

<?php
    session_start();
    if(!isset($_SESSION["username"])) {
        header("Location: login.php");
        exit();
    }
    else { 
    }
?>

It does show the correct Profile div instead of the Login  and Register div.

So I'm trying to understand what is happening here as from the look of it the $_SESSION['username'] is allocated within login.php and the session_start() function is also started in login.php

So why would I need auth_session.php to be ran in order for the correct divs to show (I've not included auth_session.php as I want people to be able to see the site that aren't logged in)

Warm regards

Link to comment
Share on other sites

It is a great idea to read the PHP Manual page on session handling.  There are many things you can configure about them, but to elaborate on kicken's answer here are a few things about Sessions that might help you understand them better.

A session has to be started with session_start() prior to you doing anything else that might cause browser output from the server to the client.  I'll explain why in a second.

A session is entirely a server-side concept. Changes that happen to the $_SESSION variable can only been accessible to your client when a request (GET/POST, etc) is made.  

By default, a session has associated serialized data in it that mirrors the contents of the $_SESSION superglobal variable.  So in your serverside php script, whatever changes are made to $_SESSION are immediately also saved/serialized, allowing you to restore them into the memory for another PHP script.

So the obvious question is:  how does PHP figure out whether a session is associated with a particular client/browser.  This is done via a session id.  The typical way the id is passed to PHP is via a cookie.

Keep in mind that the way browsers handle cookies is that, for a domain, if a browser has a cookie for that domain, it will pass all the contents of the cookie data to the server for every request.  

Also keep in mind, that the server can set cookies by including in a response header, the cookie data.

This explains why session_start() must occur before any output is sent.  session_start() determines if there is already a session that exists by reading the cookie data and seeing if it can find a matching session id,  OR it will create a new session, assign a unique session id, and add the http header to set the cookie.  As soon as a response is sent, the client/browser will set the cookie, so that in requests that follow, PHP scripts can read the stored session data into the $_SESSION variable for use in your scripts.

 

Hope this helps with your understanding.

 

Link to comment
Share on other sites

@gizmola Good information

So essentially, if hosting a fun friendly site, the SESSION can remain active to greet the user every time they visit the website?

But what if more security is desired, like a page with banking information?

What's the best way to handle a log out and elimination of the session?

Will this also eliminate the cookie?

Link to comment
Share on other sites

Sessions have expiration that you can set, as do cookies, so you have a couple different ways of handling it.  I don't want to complicate things, because the way session files are cleaned up is complicated, and highly dependent on the amount of traffic a site has. 

Also, keep in mind that a session does not equal access.  A session is just some stored data associated with a browser/client. 

So for example, let's say you allow access to a site via login, and you want that access to expire after 15 minutes of inactivity.

One way to handle that is to have a last_request column in the users table which stores a timestamp.  You can also alternatively, store that value in the $_SESSION itself.  When a "logged in" user makes a request, you have an access check that reads this value and does some simple math against it  (timestamp - last_request) and depending on the amount of time that has passed, you can allow the request to proceed, or if too much time has elapsed, remove whatever session data you have that indicates this user logged in successfully and redirect to the login page.  

Sessions are just a way to simulate a persistent connection across HTTP requests.  They can facilitate your security scheme, but they aren't providing access or rejection of anything. 

I would suggest reading about cookies.  Again they are the preferred method of session identification.  As long as you only allow secure sessions (and cookies) you can avoid a lot of security gotchas, but cookies themselves can have expiration.  Just keep in mind, that cookies like anything else that comes from the client can not be trusted.  The client should honor the cookie settings when the server tells the client to set a cookie, or expire it, but that doesn't mean that the client will do that.  For normal browsers, they certainly work as per the RFC for cookies specifies, but the request could come from some hacker who is using a modified browser or browser simulation code, that looks to your server like a regular browser, but isn't.

In general, any data you get from a client has to be considered suspect, and that includes all forms of data the server gets from the client including the data in $_COOKIE.

Most systems will include a variety of different methods to facilitate security.  For sessions, another best practice is that anytime you escalate privilege (login, access to change secure data like a password, or financial transaction) your code should regenerate the session id, and re-prompt for authentication.

I could go on in the abstract about this topic, but I really only intended to try and get you a jumpstart on your understanding, which I hope I did successfully. 

  • Thanks 1
Link to comment
Share on other sites

Hi thanks for the responses they are very informative

However I am calling start_session() in login.php (login.php is run when they login) which is my question as to why the divs are not changing when I do an if(isset($_SESSION['username'])) in the index.php (main page)

<?php
    require('dbconnect.php');

    session_start();
    // When form submitted, check and create user session.
    if (isset($_POST['username'])) {
        $username = stripslashes($_REQUEST['username']);    // removes backslashes
        $username = mysqli_real_escape_string($conn, $username);
        $password = stripslashes($_REQUEST['password']);
        $password = mysqli_real_escape_string($conn, $password);
        // Check user is exist in the database
        $query    = "SELECT * FROM `Users` WHERE User='$username'
                     AND password='" . md5($password) . "'";
        $result = mysqli_query($conn, $query) or die(mysql_error());
        $rows = mysqli_num_rows($result);
        if ($rows == 1) {
            $_SESSION['username'] = $username;
            // Redirect to user dashboard page
            header("Location: index.php");
        } else {
            echo "<div class='form'>
                  <h3>Incorrect Username/password.</h3><br/>
                  <p class='link'>Click here to <a href='login.php'>Login</a> again.</p>
                  </div>";
        }
    } else {

however when I include the auth_session.php which is the below it DOES change the divs

<?php
    session_start();
    if(!isset($_SESSION["username"])) {
        header("Location: login.php");
        exit();
    }
    else { 
    }
?>

So essentially I'm trying to figure out why after I've logged in when I DO NOT include the auth_session.php the divs for Login/Register do not change to Profile? As I run the start_Session() in the index.php

Link to comment
Share on other sites

Doh... Answered my own question as I just input session_start() into my index.php and it now works as expected...

 

I'm wondering why when login.php runs which looks like the below doesn't start the session though?!

Login.php is as follows

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Login</title>
    <link rel="stylesheet" href="style.css"/>
</head>
<body>

<?php
    require('dbconnect.php');

    session_start();
    // When form submitted, check and create user session.
    if (isset($_POST['username'])) {
        $username = stripslashes($_REQUEST['username']);    // removes backslashes
        $username = mysqli_real_escape_string($conn, $username);
        $password = stripslashes($_REQUEST['password']);
        $password = mysqli_real_escape_string($conn, $password);
        // Check user is exist in the database
        $query    = "SELECT * FROM `Users` WHERE User='$username'
                     AND password='" . md5($password) . "'";
        $result = mysqli_query($conn, $query) or die(mysql_error());
        $rows = mysqli_num_rows($result);
        if ($rows == 1) {
            $_SESSION['username'] = $username;
            // Redirect to user dashboard page
            header("Location: index.php");
        } else {
            echo "<div class='form'>
                  <h3>Incorrect Username/password.</h3><br/>
                  <p class='link'>Click here to <a href='login.php'>Login</a> again.</p>
                  </div>";
        }
    } else {
?>
    <form class="form" method="post" name="login">
        <h1 class="login-title">Login</h1>
        <input type="text" class="login-input" name="username" placeholder="Username" autofocus="true"/>
        <input type="password" class="login-input" name="password" placeholder="Password"/>
        <input type="submit" value="Login" name="submit" class="login-button"/>
        <p class="link"><a href="register.php">New Registration</a></p>
  </form>
<?php
    }
?>
</body>
</html>

 

Link to comment
Share on other sites

It's really very simple: you can not start output before session start.  You are outputting HTML at the start of your file, which sends the http header, so there's no way for PHP to provide the cookie with the session id.  

This is a big reason to have a bootstrap script or front controller so that you can do essential initialization and setup in one place.  Obviously you don't have either of those currently, but you could for now make a script named something like "initialize.php" and put things into it that you always want to do, like redirecting to https://, configuring a database connection or starting the session with session_start.  Then it's just a matter of going through other scripts and adding require_once("initialize.php") as the first line.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.