Post: [TUT]Authentication using php and mysql
05-10-2011, 01:28 AM #1
(adsbygoogle = window.adsbygoogle || []).push({});
Originally posted by 039

[align=left]SIMPLE USER AUTHENTICATION SYSTEM[/align]
Authentication system is an important part of any website now a days,which can be done in several ways .
One way of doing authentication is what we are going to discuss here.Another type is usingYou must login or register to view this content.

In this tut we will be using 7 php pages.I have divided them into 7 pages, so that it should be easier to understand and reuse.
Each and every line of code is well commented .So read the code ,use it and then if you have any doubt or you get stuck leave a reply.

Here are the seven pages.


1.login.php
This page contains the form which we will be using to submit the user name and password for authentication.Most of the work is done in this page only.

    
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php include_once("includes/constants.php");?>
<?php require_once("includes/functions.php"); ?>

<?php

// START FORM PROCESSING
if (isset($_POST['submit'])) { //Checks if the Form has been submitted.

$username = trim(mysql_prep($_POST['log'])); //collects the value of the id log which is used in the html form in the body part
$password = trim(mysql_prep($_POST['pwd'])); //collects the value of the id pwd which is used in the html form in the body part

// Check database to see if username and the hashed password exist there.Normal english //read it to understand it Happy .It is selecting id and username from the sql table users.
$query = "SELECT id, username ";
$query .= "FROM users ";
$query .= "WHERE username = '{$username}' ";
$query .= "AND Password = '{$password}' ";
$query .= "LIMIT 1";
$result_set = mysql_query($query); //mysql_query executes the query string.
confirm_query($result_set);
if (mysql_num_rows($result_set) == 1) { //mysql_num_rows calculates the number of rows returned by the execution of the query.
// username/password authenticated
// and only 1 match
$found_user = mysql_fetch_array($result_set);//mysql_fetch_array takes out the data from the array returned by the function mysql_query query and puts it inside $found_user.
$_SESSION['user_id'] = $found_user['id']; //Setting the session varaibles by using the found users id to check for the //user has loged in or not later.
$_SESSION['username'] = $found_user['username']; //Setting the session varaibles by using the found username to check for the user has loged in or not later.

redirect_to("index.php"); //redirect_to is declared inside functions.php .It redirects the page to the location given inside the quotes.
} else {
// username/password combo was not found in the database
echo "login failed ! <br><br>";
}

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>log in</title>
</head>
<body>
<a href="logout.php">logout</a> <!-- This part sends the user to logout.php..-->

<form action="login.php" method="post">
<h1>Member Login</h1>
<label for="log">Username:</label>
<input type="text" name="log" id="log" size="23" /> <!-- from here the value of log is generated -->
<label for="pwd">Password:</label>
<input type="password" name="pwd" id="pwd" size="23" /> <!-- from here the value of pwd is generated -->

<div class="clear"></div>
<input type="submit" name="submit" value="Login" /> <!-- this field submits the form.-->

</form>

</body>
</html>



2.index.php
This is the page where our users will be going after authentication .

    
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php include_once("includes/constants.php");?>
<?php require_once("includes/functions.php"); ?>
<?php
confirm_logged_in(); //calling the function confirm_logged_in() which is //declared in session.php to check if the session is set such that user has logged in.

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>log in</title>
</head>

<body>
<!---->
Thank you for logging In .Now get out.<br />
<a href="logout.php">logout</a>
</body>
</html>



3.logout.php[/size]
This is the page where all the functions regarding logging out is taken care of.

    
<?php require_once("includes/functions.php"); ?>
<?php
// Four steps to closing a session
// (i.e. logging out)

// 1. Find the session
session_start();

// 2. Unset all the session variables
$_SESSION = array();

// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/'Winky Winky;
}

// 4. Destroy the session
session_destroy();

redirect_to("index.php");
?>



4.constants.php
In this page we define all the constants to be used in the connections.php page.

    
<?php

// Database Constants
define("DB_SERVER", "localhost"); //your server name
define("DB_USER", "root"); //username of the database user
define("DB_PASS", ""); //pass for the database user
define("DB_NAME", "hf"); //database name

?>


5.connection.php[/size]
This page contains code for successful connection between php and your database.

    
<?php
require("constants.php");
global $connection;
// 1. Create a database connection
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}

// 2. Select a database
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
?>



6.functions.php[/size]
This page contains user made functions which are used later in index.php and login.php.

    
<?php
// store all basic functions

function mysql_prep( $value ) {
$magic_quotes_active = get_magic_quotes_gpc();
$new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0
if( $new_enough_php ) { // PHP v4.3.0 or higher
// undo any magic quote effects so mysql_real_escape_string can do the work
if( $magic_quotes_active ) { $value = stripslashes( $value ); }
$value = mysql_real_escape_string( $value );
} else { // before PHP v4.3.0
// if magic quotes aren't already on then add slashes manually
if( !$magic_quotes_active ) { $value = addslashes( $value ); }
// if magic quotes are active, then the slashes already exist
}
return $value;
}

function redirect_to( $location = NULL ) {
if ($location != NULL) {
header("Location: {$location}"); //$location is the name //of page to redirect to.The name is passed by the calling of the function redirect_to.
exit;
}
}

function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: " . mysql_error());
}
}

?>


7. session.php[/size]
This page contains code to start an session for the user.It also contains user defined function logged_in() and confirm_logged_in() to check for the authentication of the user.
These two functions are used in index.php and login.php

    
<?php require_once("includes/functions.php"); ?>
<?php session_start(); //It starts the session.

function logged_in() {
return isset($_SESSION['user_id']); //checking for the //value of session is set or not.
}

function confirm_logged_in() {
if (!logged_in()) {
redirect_to("login.php"); //Checks if the //session is set or not and if not then it redirects it to the login.php
}
}
?>



SQL query to create table.

For this system we will be using an simple table named users with only 3 fields.Namely id ,usename and password.

Creating database in phpmyadmin.

You must login or register to view this content.

Inserting sql code into phpmyadmin

You must login or register to view this content.

    
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` int(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;


Use phpmyadmin and input some data into fields of user to get started.Remember the name of database is hf.If you want to change that find in the constants.php the field you need to edit.
Dump some data into the fields of the table users to test the system.Use insert tab in phpmyadmin ,after clicking in the table users.

I have seen that the new comers face the difficulty in finding out, which are the inbuilt functions of the language and which are the user made functions.So here is the list of all inbuilt functions used .

INBUILT FUNCTIONS
1.You must login or register to view this content.
2.You must login or register to view this content.
3.You must login or register to view this content.
4.You must login or register to view this content.
5.You must login or register to view this content.
6.You must login or register to view this content.
7.You must login or register to view this content.
8.You must login or register to view this content.
9.You must login or register to view this content.
10.You must login or register to view this content.
11.You must login or register to view this content.
12.You must login or register to view this content.
13.You must login or register to view this content.
14.You must login or register to view this content.
15.You must login or register to view this content.
16. You must login or register to view this content.
Hope this helps you in some way .Thanks for reading and any feedback is appreciated.


source You must login or register to view this content.

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo