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
<?php // Start session session_start(); // Echo username and id echo $_SESSION['username'].$_SESSION['id']; ?>
Mail this!
- Comments (0)
- PingBacks (0)
- TrackBacks (0)

» Latest comments