Session question


I am creating a PHP forum, and have used session_start(); at the top of my pages. How do I make it so it forces the user to be logged in? How would I check if the session has started?


you would have some sort of login form/page.
Check those values are in your db and are correct.
If so, save the values of the login variables to session ones, then after session_start check to make sure the variables you have that make you ‘logged in’ are set and valid.
If not redirect (using header: ) to go to your login page.

So, it would essentially be…

if ($_SESSION['username'] != '' )
		echo "Logged in as: " . $_SESSION['username'];
		header("location: login.php");

Thats what I have at the top of the page, and it directs me to the login page, and allows me to login, but then when I click the link that forced me to login, it makes me login again. Does that make sense?

when and where are you setting your $_SESSION vars

imho this is a huge no-no :disagree: , especially for the password.

if you want to display the user’s username on each page after they log in then you can save the username in a sesion var., but for no other reason.

regarding validating if someone is logged in this is the basic steps you could take

  1. send the username/passowrd in the login form to a server side script.

  2. the server side script then checks if the username/passowrd exists in the database.

  3. if it does, set a hard to guess session variable key and value

  4. then on every page where login needs to be verified, immediately after session_start() check if the session var from 3) exists and if it is set to the value set in 3). If it is, alow the page to continue loading. If it isn’t then display an appropriate error message and terminate the loading of that page.