Jump to content

check is logged in


Recommended Posts

how can i check that the user is logged in on a webpage?currently i have this on the page you are directed to when you have successfully logged in:<? session_start();if(!session_is_registered(myusername)){header("location:login.php");}?>which immediately returns you to the login page which i think is because i changed session_register() to $_SESSION[] on the checklogin page, this is what i have now: $_SESSION['username'] = $myusername; $_SESSION['password'] = $mypassword;how do i check this? im thinking i need to change:session_is_registeredto something else? any help would be great

Edited by beennn
Link to comment
Share on other sites

You can check the value of a session variable just like you would any other variable.But putting session_start() at the beginning of a page, all session variables are accessible.

session_start();if(isset($_SESSION['username'])) {  echo $_SESSION['username'];}

Important: If you're setting session variables on a page that sends a location header, use session_write_close() right before sending the header or the values will not be saved.

session_write_close();header('Location: ---');

Explanation: Right after a script finishes running, the PHP engine save the session values. When you send a location header, the page may redirect before the script has time to finish executing and saving the session values.

Link to comment
Share on other sites

if you are working with the SESSION array, a way to check if they are _not_ there could be like this:

<? session_start();if(empty($_SESSION['username']) && empty($_SESSION['password'])){  header("location:login.php");}else{  //good to go};?>

this would be after validating that the username and password have been authenticated. I think typically one takes the login username/password, checks it against the database, and then just sets single $_SESSION variable to check on all pages, like so:

<?php  session_start();  //check POST/GET params against DB to authenticate user  //is it checks out, set a flag  $_SESSION['logged_in_user'] = true;  if($_SESSION['logged_in_user']){	//show the user the page  }else{	//else redirect back to login page  };?>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...