In this tutorial, I will explain step by step how to create a login page in PHP.
Create a table Users in your mySQL database.
CREATE TABLE `Users` (
`id` int(4) NOT NULL auto_increment,
`user_name` varchar(100) NOT NULL default '',
`password` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;
For testing purpose, run the following sql query to inset a row into the database:
INSERT INTO `Users` VALUES (1, 'feras', 'pass');
Create login.php page with the following HTML controls:
A form. Name it as frm, set the action property as validatelogin.php
Text Box for uesrname. Name it as user.
Text Box for password. Name it as password.
Submit Button. Name it as login
Your form should look like this:

Create validatelogin.php:
$hostname="hostname"; // hostname, use localhost for local machine
$username="dbusername"; // database username
$password="dbpassword"; // databanse password
$db_name="myDatabase"; // Database name //
//create connection to the server
mysql_connect("$hostname", "$username", "$password")or die("connecting failed");
// select the database
mysql_select_db("$db_name")or die("Error selecting database");
// username and password variable from the form ( see code above)
$username=$_POST['user'];
$password=$_POST['password'];
$sql="SELECT * FROM Users WHERE user_name='$username' and password='$password'";
$sqlresult=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($sqlresult);
// if matched, count should be 1
if($count==1){ // create username and password sessions, and redirect to login succeed
session_register("username");
session_register("password");
header("location:loginsuccess.php");
else
{ echo "Login failed"; }
ob_end_flush(); // for php5 users
Create the loginsucceed.php file:
session_start();
if(!session_is_registered(username)){
header("location:login.php");
echo 'Welcome to the members area!';
}
Create logout.php page to kill the session:
session_start();
session_destroy();
This is a simple login page. However, it requires some additional coding to prevent sql injection, malicious behaviors and to encrypt the password in the database. You may check Prevent SQL Injection with PHP and MySql and Encryption Password using md5() function.




