Online: 103   Members: 4,232

User Login With Sessions

The following tutorial shows you how to make a user login system with sessions. The first step is to create a username and password, do this by making a file called config.php which will contain the following code:

<?
$username = "admin";
$password = "pass";
?>

Now that they have been initialized, we can continue on to the actual login page. Create a file called index.php and start it off with the following:

<?
require ("config.php");
session_start();
if ((!$username) || (!$password))
{
	echo '<form name=login method=post action="">
	user:<input type=text name=user><br>
	pass:<input type=text name=pass><br>
	<input type=submit value=go>
	</form>';

}

This piece of code essentially checks to see if the username and password are being submitted from the login form. If not that means it needs to show the form itself. Next, we add the code that checks the forms responses against the values stored in the config.php file.

else
{
	if($user==$username && $pass==$password)
	{
		session_register("username");
		session_register("password");

		echo "Congratulations &username, you have logged in!<br>
		<a href=\"?logout=1\" >Logout</a>";

	}
	else
		echo "Incorrect Password please <a href=?index.php?>try again</a>";

}

Lastly, we need to add the code that allows the users session to be terminated when they sign out. This is done simply by unregistering the session variables as follows:

if($logout==1)
{
	session_unregister("username");
	session_unregister("password");
}
?>

With some slight modification this script can be altered to use multiple username/passwords as well as checking against a database of users.

Related Tutorials

Useful Resources