Building your own Myspace.com with PHP Part III: Register and log in with sessions

Posted by Stefan on July 31st, 2007 at 08:58pm

In this third part of the tutorial we are going to create an important part of the application. We will learn how to register a new user and save this user to the database, when a user is created it should of course be possible for him to log in. We will accomplish the login part by using session variables.

Well lets start with how to register a user. The first thing we will need is some text boxes with html to put in the desired username and password.

 
<form action="signup.php?submit" class='form colours' method='POST'>
	<fieldset>
		<legend>Join my community</legend>
			<p align='right'>Username: <input name='username' size='25' maxlength='25' /></p>			
			<p align='right'>Password: <input name='password' size='25' maxlength='25' /></p>	
                        <p align='right'><input type='submit' value='Submit' /></p>
	</fieldset>
</form>

This code creates two text boxes that is supposed to hold the username and password, when the form is submitted the contents of the text boxes is forwarded to the file signup.php.

<?php
// Check if the form has been submitted
if(isset($_GET["submit"]))
{
	if(isset($_POST["username"]) && isset($_POST["password"]))
	{	
		//Username or password is not blank
		if($_POST["username"]!="" && $_POST["password"]!="")
		{ // Everything is ok add the user to the database
 
			// Connect to the database
			require_once("classes/DbConnector.php");   // Include the database class
			$db = new DbConnector();               // Create an instance of the database class
			$db->connect();                               // Connect to the database
			$query = "SELECT * FROM members WHERE username='".$_POST["username"]."'";
			$result = $db->query($query);
			$result = mysql_num_rows($result);
 
			if($result!="0")
				echo "Username already exists!";
			else 
			{ 
				// Create a query that inserts the data from the form to the database
				$query = "INSERT INTO members(username,password) VALUES('".$_POST["username"]."','".$_POST["password"]."')";
 
				$result = $db->query($query);
				echo "Signed up succesfully you can now <a href=\"login.php\">log in</a>";
			}
		}
		else 
		{
			echo "Error: No username or password supplied, try again.";
		}
 
	}
	else 
		echo "Error: please fill in the <a href=\"signup.php\">signup form</a>";
}
?>

The first thing this file does is to check if we have valid data submitted from the html form we created above we do this using the php functions $_GET and $_POST. Get is used to get variables passed from file to file with php as from our example above (signup.php?submit) we set the variable submit as the forms submit button is pressed. Post is used to get data passed from a form in the example above we get the values of the text boxes where the username and password is written.

When we have made sure we have valid data in these variables we proceed and sets up a connection to the database and trues to select the username from the database. We do this to make sure we don get any duplicate entries. If the username does not exist we can proceed and insert the new data into the database.

The next step is to log in, as mentioned above we will use sessions for this task. First we create a html form like above but instead of calling signup.php we call login.php

<?php
// login.php
session_start();
if(isset($_GET["submit"]))
{
	login($_POST["username"],$_POST["password"]);
}
function login($username,$password)
{	
	require_once("classes/DbConnector.php");
	$db = new DbConnector();
	$db->connect();
	$query = "SELECT * FROM members WHERE username='$username' AND password='$password'";
	$result = $db->query($query);
	$result = mysql_num_rows($result);  // Does the row exists?
 
	if($result!="0"){ 
	// authenication correct lets login
	$_SESSION["password"] = $password;;
	$_SESSION["username"] = $username;
	header("Location: member.php?id=$username");
	}
	else 
	{
		echo "Wrong username or password. Please try again!";
	}
}
?>


This code first checks to see if the username exists if it does it goes on to make sure the password is correct. If everything looks correct it registers two session variables with $_SESSION called username and password and forwards the user to our main page member.php.

Next part: Presentation

Under PHP+ Tutorials

4 Comments for Building your own Myspace.com with PHP Part III: Register and log in with sessions

  • 1. ellisgl  |  August 10th, 2007 at 9:16 pm

    Make your session stronger by:
    session_start(); // Start the session

    // Simple protection of session attacks.
    if(!isset($_SESSION['init']))
    {
    session_regenerate_id();
    $_SESSION['init'] = 1;
    }

  • 2. Anders Moen  |  September 16th, 2007 at 5:47 pm

    There’s a security hole in the login!
    I wrote ‘ as username and - as password and voila - logged in.

    You should use mysql_real_escape_string() around the variables

  • 3. Dale  |  June 6th, 2008 at 11:54 pm

    not working for me

    made some one can do for me im new to code

    Email me If you can help me dksnowdon@googlemail.com

    Thanks Dale

  • 4. Rob Foley  |  June 29th, 2008 at 9:21 am

    I must be missing something i got it to register into the database. But for login and for member.php it just goes to a blank white page so obviously the echo’s arent working. Anyone have any related problems or ideas on how to fix it

Leave a Comment for Building your own Myspace.com with PHP Part III: Register and log in with sessions

hidden

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Blog Posts

Categories

Posts by Month

Blogroll