Simple login and PHP handler

Views: 298 Last modified: August 03rd, 2011 Comments: 0

This is a nice example of how to build an login area in php.
This simple login example contains sessions as well from login.php to member_profile.php, off course you can extend it with many more pages.

This is done by using different pages but you can combine all of them into 1 single page.
You can modify this however you want!

login-handler.php

<?php
// Database refs
require_once 'db.php';

// start session
session_start();

if ( $_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['confirm'] == 'confirmed' )
{
	// Check if username and password arent empty
	if ( ! empty( $_POST['username'] ) && ! empty( $_POST['password'] ) )
	{
		// Escape characters, uses simple md5
		$username = sprintf( '%s', mysql_real_escape_string( $_POST['username'] ) );
		$password = sprintf( '%s', md5( mysql_real_escape_string( $_POST['password'] ) ) );

		// Get records
		$result = mysql_query( "SELECT *
                                    FROM members
                                    WHERE mem_name = '$username'
                                    AND mem_pass = '$password'" );

		// If result is not 1, die with message
		if ( ( int )mysql_num_rows( $result ) != 1 )
			die( 'User/Password combination isnt correct' );

		// Assign session variables
		$_SESSION['username'] = mysql_result( $result, 0, 1 );
		$_SESSION['id'] = mysql_result( $result, 0, 0 );

		// Go to member page
		header( 'Location: http://localhost/tests/little_scripts/member_profile.php');
	}
    else
	{
		die( 'One or both the fields were empty. Please try again.' );
	}
}
else
{
	// If session_start has been entered
	if ( isset( $_SESSION ) )
	{
		// Unset session
		@session_unset();

		// Destroy session data/files
		@session_destroy();

	}

	// Go to login page
	header( 'Location: http://localhost/tests/little_scripts/login.php' );
}
?>

login.php

<?php
// initialize session
session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
	<title>Login</title>
</head>

<body>
    <form method="POST" action="login-handler.php">
        <p>Username: <input type="text" name="username" /></p>
        <p>Password: <input type="password" name="password" /></p>
        <input type="hidden" name="confirm" value="confirmed" />
        <p><input type="submit" name="login" value="Login!" /></p>
    </form>
</body>
</html>

member_profile.php

&lt;?php
// Start session
session_start();
// Echo username and id
echo $_SESSION['username'].$_SESSION['id'];
?&gt;
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {0+3} =  
    Anything to add ?

        You must be logged in to post a comment.