Post: [TUTORIAL] Create a login using PHP and MySQL [TUTORIAL]
05-10-2011, 12:43 AM #1
(adsbygoogle = window.adsbygoogle || []).push({});
Originally posted by 039

Hey guys.

, but i've been coding PHP for quite a while.

In this tutorial i'm going to show you HOW to make a login script including a member-only site and logout using MySQL and sessions.

So - let's get to it!

[size=medium][b]Step one:[/b][/size]
Do the structure thinking

The first thing we have to do is to think about the structure.

Are we using a class? (no need here)
How should we prevent injections?
How should the files be divided?
// Tutorial:
I'm going to add explanatory after each code line doing the tutorials.

Basically the first step should be all considerations regarding coding and structure of the system. Since our little script here is so small, we shouldn’t do much about this section.

[size=medium][b]Step two[/b][/size]
Basic coding – login form

When it comes to a login/logout system, a login-page is pretty much necessary.
It's going to contain two sets of text-inputs and a submit input, just a simple html-form:

    
<!—Login.html --!>

<form action="" method="POST">
<p>Username:</p>
<input type="text" name="username" />

<p>Password</p>
<input type="password" name="password" />

<br />
<input type="submit" name="doLogin" value="Log me in" />
</form>


As you see, we're just using a simple form with a target of doLogin.php. We're using simple paragraphs tags wrapping the text – (laziness – block-tags, no need to add a newline, hurray!).

[size=medium][b]Step three[/b][/size]
Validating credentials / inputs

A very important step of creating a login-system is the validation part. This is the step where we're checking if a user exists or not, checking for wrong passwords etc.

    
<?php
// Login.php
session_start(); // Starts the session so we're able to communicate later on.

$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'HFLogin';

$conn = mysql_connect($db_host, $db_user, $db_pass); // Sets a connection to a database
mysql_select_db($db_name , $conn); // Selecting a db

// Post variables

$username = trim(strip_slashes($_POST['username'])); // Username variable to later use.
$password = trim(strip_slashes(sha1($_POST['password']))); // Sets a password variable to later use.

// Selects a user from the database where username and password is equal to the inputs.
$getLogin = mysql_query("SELECT username, password, id FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."' LIMIT 1") or die(mysql_error());
// Creates an array of the fetched results from the query.
$thisUser = mysql_fetch_array($getLogin);
// Creates an variable counting the results from the query.
$countResults = mysql_num_rows($getLogin);

// If a result is found then login.. (we can do this since we checked both the password and username in the query)
if($countResults == 1):
// Sets a session (isLoggedIn) equals to true. Now we can check if this session is active on the memberpage.
$_SESSION['isLoggedIn'] = true;
$_SESSION['username'] = $username;
// Redirect to a member page.
header("Location : memberPage.php");
else:
header("Location : login.html");
endif;
?>


So, we have our login-form ready and ready for use. For you to use this, you'll have change the first 4 variables to our database connection.

[size=medium][b]Step four[/b][/size]
Creating our member page

Now we're creating our members only page. This is actually pretty simple as we created a couple of sessions in our doLogin.php page. Now we can just validate if these sessions are true, and if they are, then show the members only page, otherwise redirect to login.html.

    
<?php
// membersOnly.php

session_start();

// Check if our sessions are inactive
if($_SESSION['isLoggedIn'] != TRUE && ! isset($_SESSION['username'])):
header("Location : login.html");

// If they're active THEN show our members only site.
else:
echo "Hello ". $_SESSION['username'];
echo "<br />";
echo "You are logged in, hurra. Underneath you will see some members only functions.";
echo "<br />";
// Logut link!
echo "<a href=\"logOut.php\">Log me out</a>";
endif;
?>


Now our login section, members only section are complete. Our only task is to create a proper logout script. This is rather simple as we're using sessions.

[size=medium][b]Step five[/b][/size]
Creating our logout script

For this system to work, we need to unset our user-sessions that we created in our login script.

The system is rather simple:

    
<?php
// doLogout.php
session_start(); // Starts the sessions to retrieve our earlier sat sessions.

// Unset our username session
unset($_SESSION['username'];
// Unset our isLoggedIn session
unset($_SESSION['isLoggedIn'];

// Destroy all sessions
session_destroy();

// Redirect to our login-page
header("Location : login.html");
?>


[size=medium][b]Step six[/b][/size]
Our MySQL table

This step should actually be the first step, but as we simply just started with the raw codes, our table is here.

Our table is rather simple, containing a id, username and password:

    
CREATE TABLE IF NOT EXISTS `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


[size=medium][b]Step seven[/b][/size]
Wrapping up

Now we've created our very own login system, sessions are our main keys inclusive our database.

I hope you enjoyed this tutorial, and if needed, I might return.


source You must login or register to view this content.
Last edited by CodingNation ; 05-10-2011 at 12:45 AM.

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo