PHP practical example using sessions with private content login system
Nov 09, 2010
Author: Dr_ViRuS
A few days ago the students of Faculty of Informatics in some place got a exam One of the tasks was to make a 3 pages. page3.php is private and should login with username and password. The structure of the task is:
Page1.php
Page2.php
Page3.php - private
Form3.php - form for login in
Attention this task is a classical example The main goal of the task is to show practical use of php sessions.
page1.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Login</title> </head> <body> <a href="page2.php">Page 2 Public</a> <a href="page3.php">Page 3 Private</a> </body>
page2.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Loign</title> </head> <body> <h1>This is public page </h1> <a href="page1.php">Page 1 Public</a> <a href="page3.php">Page 3 Private</a> </body> <html>
page3.php
<?php
session_start();
if (!$_SESSION['loged'] )
{
header("Location:form3.php");
die();
}
if ($_GET["logout"] == true)
{
session_destroy();
header("Location:form3.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>login</title>
</head>
<body>
<p>Private content</p>
<p><a href="?logout=true">Logout</a></p>
<a href="page1.php">Page 1 Public</a>
<a href="page2.php">Page 2 Public</a>
</body>
</html>
form3.php
<?php session_start();
if ($_SESSION['loged'] == true)
{
header('Location: page3.php');
}
if ($_POST['submit'])
{
if ($_POST['username'] == 'douglas.adams' && $_POST['password'] == 'hitch42hike' )
{
$_SESSION['loged'] = true;
header('Location: page3.php');
}
else
{
$error_login = "Wrong username and password";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login</title>
</head>
<? if ($error_login)
{
echo "<p>$error_login</p>";
}
?>
<form method="post" action="">
<label>User name</label>
<input name="username" type="text" /><br />
<label>Password</label>
<input name="password" type="password" />
<br />
<input type="submit" value="Login" name="submit" />
</form>
<body>
<a href="page2.php">Page 2 Public</a>
<a href="page1.php">Page 1 Public</a>
username and password douglas.adams i hitch42hike
</body>
</html>
You can also check PHP login example whit MySQL
views 6077



