Thursday, 30 October 2014

Create Login Page in PHP and MySQL with Session

Hello readers , hope you are good.

Today i will explain  "how create a login page using PHP/MySQL with Session.".
As i am consider that you have intermediate knowledge of PHP and MySQL.

I am explaining term : "SESSION"

First understand the concept behind session :
Suppose you have to work with an application , you open it, do some changes and then you close it. This is much like a Session.

 The computer knows who you are. It knows when you start the application and when you end.

But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

 A PHP session solve this problem by allowing you to store/hold user information on the server.However, session information is temporary and will be deleted after the user has left the website.
If you need a permanent storage you may want to store the data in a database.
 so we can use session to store/hold temporary information.

  How SESSION store values : 
 Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

  SESSION in php coding :

<?php session_start(); // Starting a PHP Session , this must be declare before html tag.

$_SESSION['IsLogin']="Yes"; // store session data
 ?>
 <html>
    <body>
       <?php
        //retrieve session data
           echo "User Logged-in =". $_SESSION['IsLogin'];
     ?>
    </body>
 </html>


We will create Login page in 6 steps 

1. Configure the MySQL Database
2. Create a MySQL table name "users"
3. Create a test row in table "users"
4. Database connection.
5. Create PHP Login and Logout Function.

1. Configure the MySQL Database


CREATE DATABASE `login_test`;


2. Create a MySQL table name "users"


CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` VARCHAR(50) NOT NULL,
`email` VARCHAR(80) NOT NULL,
`password` CHAR(128) NOT NULL
) ;


3. Create a test row in table "users"


INSERT INTO `users` (
`id` ,
`username` ,
`email` ,
`password`
)
VALUES (
NULL ,
'test',
'test@test12.com',
'test'
);


4. Database connection



For database connection we create separate file db.php
db.php contains bellow database connection code.
<?php

DEFINE ('DB_USER', 'root'); // The database username.

DEFINE ('DB_PASSWORD', '');  // The database password.

DEFINE ('DB_HOST', 'localhost');  // The host you want to connect to.

DEFINE ('DB_NAME', 'login_test'); // The database name.
     
?>
Remaining part in 2 days