Login And Logout With Session In PHP – Info PHP
Introduction
This article explains login and logout with session in PHP. You will first create a database and a table named login and then create a login form with simply two fields, username and password. Then you will make a connection with your MySQL table “login” and enter some PHP code. I will use a session for authentication purposes in login and logout.
Example
First of all, create the “index.php” file as in the following:
a{
float:left;
text-decoration:none;
padding:0px 2px 0px;
}
h1{
color:#008844;
font-size:20px;
text-align:center;
}input{
background-color:#33FFFF;
color:#000;
}
“signup.php”>“submit” name=“submit” value=“Signup”> “Login.php”>“submit” name=“submit” value=“login”>
Welcome to my website
Output
This is your “login.php” file.
$error=“”;
mysql_connect(“localhost”,“root”,“”)or dir(mysql_error());
mysql_select_db(‘demo’);
session_start();
if(isset($_POST[‘submit’])){
$username = $_POST[‘username’];
$password = $_POST[‘password’];
if
$query=“SELECT id FROM login WHERE username=’$username’ and password=’$password'”;
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$id=$row[‘id’];
$count=mysql_num_rows($result);
if($count==1)
{
//session_register(“username”);
$_SESSION[‘name’]=$username;
header(“location: welcome.php”);
}else{
$error = ‘please enter username and password’;
}
}
}
?>
“-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
“http://www.w3.org/1999/xhtml”>
“Content-Type” content=“text/html; charset=iso-8859-1” />
input{
color:#4A0000;
border:1px solid #4A0000;
}
action=“” method=“post”>
Output
This is your “secure.php” file.
mysql_connect(“localhost”,“root”,“”)or dir(mysql_error());
mysql_select_db(‘demo’);
session_start();
$check=$_SESSION[‘name’];
$query=mysql_query(“select username from login where username=’$check’ “);
$data=mysql_fetch_array($query);
$user=$data[‘username’];
if(!isset($user))
{
header(“Location: login.php”);
}
?>
This is your “welcome.php” file.
a{
float:left;
text-decoration:none;
}h1{
color:#008844;
font-size:20px;
text-align:center;
}
include(‘secure.php’);
if($_SESSION[‘name’]){
echo ‘‘;
}else{
echo ‘‘;
}
?>
Welcome to the my secret area
Output
When you will click the on “logout.php” button your session will be clean and redirect to the login page.
session_start();
if(session_destroy())
{
header(“Location: login.php”);
}
?>
Output
Article Prepared by Ollala Corp