Asked  7 Months ago    Answers:  5   Viewed   41 times

I have just finished creating an entire login and register systsem in PHP, but my problem is I haven't used any sessions yet. I'm kind of a newbie in PHP and I've never used sessions before. What I want to do is, after the user registers and fills out the login form, they will still stay on the same page. So, there will be one part of the which will be if the session is logged_in and the other part will be else (the user is not logged in so display the login form). Can anyone tell me how to get started?

 Answers

84

Hope this helps :)

begins the session, you need to say this at the top of a page or before you call session code

 session_start(); 

put a user id in the session to track who is logged in

 $_SESSION['user'] = $user_id;

Check if someone is logged in

 if (isset($_SESSION['user'])) {
   // logged in
 } else {
   // not logged in
 }

Find the logged in user ID

$_SESSION['user']

So on your page

 <?php
 session_start();


 if (isset($_SESSION['user'])) {
 ?>
   logged in HTML and code here
 <?php

 } else {
   ?>
   Not logged in HTML and code here
   <?php
 }
Wednesday, March 31, 2021
 
Amber
answered 7 Months ago
12

Yes, this is called "session locking" and is normal in PHP.

One solution is not not use sessions, just set cookies for your required persistent information.

Another solution is to implement your own session handler:

http://php.net/manual/en/session.customhandler.php

A detailed walkthrough about custom MySQL session handlers is here:

http://phpmaster.com/writing-custom-session-handlers/

Wednesday, March 31, 2021
 
capsid
answered 7 Months ago
46

Start Session in head.php page.

head.php

<?php
if($pagename != "login") {
  session_start();
  if(!$_SESSION['login']) {
    header('location: login.php');  
    exit();
  }
}
?>
Saturday, May 29, 2021
 
eliotlencelot
answered 5 Months ago
33

Small example that I often use

function setSession($username,$password,$cookie=null){
    // Other code for login ($_POST[]....)
    // $row is result of your sql query
    $values = array($username,$this->obscure($password),$row['id']);         
    $session = implode(",",$values);

    // check if cookie is enable for login
    if($cookie=='on'){
        setcookie("your_cookie_name", $session, time()+60*60*24*100,'/');
    } else {
        $_SESSION["your_session_name"] = $session;
    }
}
Sunday, July 11, 2021
 
RenegadeAndy
answered 4 Months ago
90

First up: you should never, ever, use md5 to hash passwords. Read this article on why, and then use Go's bcrypt package. You should also parameterise your SQL queries else you are open to catastrophic SQL injection attacks.

Anyway: there are a few problems you need to address here:

  • Your sessions aren't "sticking" is that you're setting the Path as /loginSession - so when a user visits any other path (i.e. /), the session isn't valid for that scope.

You should be setting up a session store on program initialisation and setting the options there:

var store = sessions.NewCookieStore([]byte("something-very-secret"))

func init() {

   store.Options = &sessions.Options{
    Domain:   "localhost",
    Path:     "/",
    MaxAge:   3600 * 8, // 8 hours
    HttpOnly: true,
}

The reason you might set a more specific path is if logged in users are always within a sub-route like /accounts. In your case, that's not what's happening.

I should add that Chrome's "Resource" tab in the Web Inspector (Resources > Cookies) is incredibly useful for debugging issues like these as you can see the cookie expiry, path and other settings.

  • You're also checking session.Values["email"] == nil, which doesn't work. An empty string in Go is just "", and because session.Values is a map[string]interface{}, you need to type assert the value to a string:

i.e.

if val, ok := session.Values["email"].(string); ok {
      // if val is a string
      switch val {
             case "":
                 http.Redirect(res, req, "html/login.html", http.StatusFound)
             default:
                 http.Redirect(res, req, "html/home.html", http.StatusFound)
      }
    } else {
        // if val is not a string type
        http.Redirect(res, req, "html/login.html", http.StatusFound)
    }

We deal with the "not a string" case so we're explicit about what the program should do if the session is not how we expected (client modified it, or an older version of our program used a different type).

  • You are not checking errors when saving your sessions.

    sessionNew.Save(req, res)
    

... should be:

    err := sessionNew.Save(req, res)
    if err != nil {
            // handle the error case
    }
  • You should get/validate the session in SessionHandler before serving static files (you are doing it in a very roundabout way, however):

    func SessionHandler(res http.ResponseWriter, req *http.Request) {
        session, err := store.Get(req, "loginSession")
        if err != nil {
            // Handle the error
        }
    
        if session.Values["email"] == nil {
            http.Redirect(res, req, "html/login.html", http.StatusFound)
        } else {
           http.Redirect(res, req, "html/home.html", http.StatusFound)
        }
        // This shouldn't be here - router isn't scoped in this function! You should set this in your main() and wrap it with a function that checks for a valid session.
        router.PathPrefix("/").Handler(http.FileServer(http.Dir("../static/")))
    }
    
Monday, August 9, 2021
 
jsuissa
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :