Php login form | php login script with mysql

Here we making simple php login script or php login form or php login page whatever you may say.Php login script, we are using Mysql database to store users' data and session is used to track, whether or not user logged in ? First we need to create user table in database with three fields id,username and password. the query is given below:
CREATE TABLE users(id int AUTO_INCREMENT PRIMARY KEY,username varchar(45)
,password varchar(15));
The above query will create table. Now insert some data in users table.
INSERT INTO users(username,password)VALUES('demo','pass');
Or you can make registration script yourself as given in tutorial Php Registration Form | Php Registration Script With Mysql. Our first step is completed for php login script. Now second step is making php login form.
<!-- login.php-->

<form name="login_form" id="login_form" method="post" action="login_check.php">
<table> <tr><td colspan="2"><?php echo isset($_GET["msg"])?$_GET["msg"]:"";?> </td></tr>
<tr><td>Username</td><td><input type="text" name="username" id="username" /> </td></tr>
<tr><td>Password</td><td><input type="password" name="password" id="password" /> </td></tr>
<tr><td></td><td><input type="submit" name="btnsubmit" id="btnsubmit" /> </td></tr>
Our php login form is ready.As you see, here action attribute is set login_check.php. This is the page, where our form's data is submitted. And on this page we will check from users table whether user exists or not. And line <?php echo isset($_GET["msg"])?$_GET["msg"]:"";?>. prints error message if user returns on login.php due to some validation error. Now our third step is making this page.

<?php //login_check.php session_start();
///open connection
$link=mysql_connect($host,$user,$pass) or die(mysql_error());
$query="SELECT * FROM users WHERE username='".mysql_escape_string($username)."' AND password='".mysql_escape_string($password)."'";
//count no of rows
$_SESSION["username"]=$username; header("location:index.php");
header("location:login.php?msg=user not found");

header("location:login.php?msg=Username or password caanot be blank.");

Next step is making landing page for user after login. Before doing anything on this page session for login is checked.If session is not found then user is redirected to login page with header function.

<?php //index.php file session_start(); //redirect for login if,user is not logged in
<title>User Area</title>

Welcome <?php echo $_SESSION["username"]?> | <a href="logout.php">Logout</a>

As you see, logout link is given on index.php page. Now our final step is making logout page. Where we unset session for login and redirect user to login.php page.

session_start(); if(isset($_SESSION["username"])){
header("location:login.php"); }

Happy coding