Monday 4 February 2013

PHP & MYSQL LOGIN with SESSION

How to Create Login Page in PHP and MySQL with Session

The production of login page using PHP and MySQL is actually very simple. I assume that you use local web server connection (Apache and PHP) and your MySQL database configuration use ‘localhost’ as hostname and ‘root’ as username with blank password.

For this case, I recommend you to using XAMPP (http://www.apachefriends.org/en/xampp-windows.html).

Please download and install it to your path choice. e.g: C:\xampp
Run XAMPP Control Panel on desktop.

Start Apache and PHP modules.


Let’s create a database with PHPMyAdmin. Open your favorite browser, then type ‘http://localhost/phpmyadmin’ at your browser address bar.
Create database ‘phpmysimplelogin’.

Click ‘Create’.
Now, let’s create a table, name it ‘user’ with ’2′ (two) number of fields.








Click ‘Go’.
First field, name it ‘username’, type ‘varchar’, lenght/values ’25′.
Second field, name it ‘password’, type ‘varchar’, lenght/values ’255′.


Click ‘Save’.


After that, we will fill the table. Click ‘SQL’ menu, then type this query on textbox:
INSERT INTO user (username, password) VALUES (‘admin’, md5(‘admin’))
Click ‘Go’.
It means, you fill ‘username’ field with string ‘admin’ and ‘username’ field with an encryption string of ‘admin’. MD5 ia a function to create one-way encryption (hashing) from our password, so it can be more secure.


Okay, now let’s prepare the web pages.
Create folder ‘phpmysimplelogin’ in your XAMPP’s htdocs. So, it will be ‘C:\xampp\htdocs\phpmysimplelogin’.

Remember to save all of your files you will create, inside this folder.
Run your favorite PHP code editor, e.g: PHP Expert Editor, RapidPHP, etc; or just Microsoft Notepad is fine.
Save document below with name ‘config.inc’.

<?php
$hostname = 'localhost';     
$dbname   = 'phpmysimplelogin'; // Your database name.
$username = 'root';             // Your database username.
$password = '';                 // Your database password.
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed');
// Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');
?>

Next step, save document below and name it as ‘index.php’:

<?php
// Inialize session
session_start();
// Check, if user is already login, then jump to secured page
if (isset($_SESSION['username'])) {
header('Location: securedpage.php');
}
?>
<html>
<head>
<title>PHPMySimpleLogin 0.3</title>
</head>
<body>
<h3>User Login</h3>
<table border="0">
<form method="POST" action="loginproc.php">
<tr><td>Username</td><td>:</td><td><input type="text" name="username" size="20"></td></tr>
<tr><td>Password</td><td>:</td><td><input type="password" name="password" size="20"></td></tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="submit" value="Login"></td></tr>
</form>
</table>
</body>
</html>
As you see, there is ‘session_start();’.

This function is used to initializes a data session. It will creates a new session or continues previous session from data session changed by GET, POST or cookie.
See the detail information about session here:http://id.php.net/function.session-start

Now, prepare a file and give it name ‘loginproc.php’ to check the validity of username and password.

<?php
// Inialize session
session_start();

// Include database connection settings
include('config.inc');

// Retrieve username and password from database according to user's input

$login = mysql_query("SELECT * FROM user WHERE (username = '".mysql_real_escape_string($_POST['username'])."') and (password='".mysql_real_escape_string(md5($_POST['password']))."')");

// Check username and password match
if (mysql_num_rows($login) == 1) 
{
// Set username session variable
$_SESSION['username'] = $_POST['username'];
// Jump to secured page
header('Location: securedpage.php');
}
else 
{
// Jump to login page
header('Location: index.php');
}
?>

If username and password are correct, then we’ll be directed to ‘securedpage.php’.

This is the page that we want to show if login is successful. This page cannot be accessed if the correct data session is not found when login check is passed.

This page also contains ‘logout’ menu, so we can destroy our login data session then return to login page.

This is content of ‘securedpage.php’:

<?php
// Inialize session
session_start();

// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['username'])) {
header('Location: index.php');
}
?>
<html>
<head>
<title>Secured Page</title>
</head>
<body>
<p>This is secured page with session: <b><?php echo $_SESSION['username']; ?></b>
<br>You can put your restricted information here.</p>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
This is content of ‘logout.php’:
<?php
// Inialize session
session_start();

// Delete certain session
unset($_SESSION['username']);

// Delete all session variables
// session_destroy();
// Jump to login page

header('Location: index.php');
?>

Now Open your Favorite browser and run your localhost:
http://localhost/phpmysimplealogin/

And enjoy!!

No comments:

Post a Comment