Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Protecting a Page with Sessions (0 Comments)
Admin: Posted Date: March 3, 2010

First of all, create a basic form that goes to login.php. Then, on the login.php page we need to first open PHP tags, and start by adding ob_start(); (this allows a header location tag to be placed anywhere in a script without it showing errors).

PHP Tutorial - Protecting a Page with Sessions

index.php

First of all, create a basic form that goes to login.php.

	<form action="login.php" method="POST">
	Pass Code: <input type="password" name="passcode"><br>
	<input type="submit">
	</form>
	

login.php

Then, on the login.php page we need to first open PHP tags, and start by adding ob_start(); (this allows a header location tag to be placed anywhere in a script without it showing errors). Then beneath it, you need to start the session ( session_start(); ). Now that is done, next we'll need to make an IF statement asking if the passcode given from the form on index.php matches the value we give it (In the example, 12345 is used). Then set the sessions name as 'canview' and the value of it to "yes", this'll set the session called canview with a value of 12345. Beneath that you will need to then add a header(); tag, redirecting you to the secret page.
If you enter the wrong information then you want the script to give an error, so add an ELSE statement underneath and within it add a die(); tag.
<?php
ob_start();
session_start();
if($_POST[passcode] == "12345") {
     $_SESSION['canview'] = "yes";
     header("Location: secret.php");
} else {
     die("Wrong Passcode");
}
?>


secret.php

Once you have entered the correct information you will be forwarded to secret.php and that is where your secret information will be viewable, if you have entered the correct passcode. Any information you wish to protect, then place it between the IF and } ELSE { lines.
Code:
<?php
session_start();
if($_SESSION['canview'] == "yes") {
     echo "This is a secret page!!";
} else {
     die("Please login");
}
?>

logout.php

Then to logout, that is very simple, all you do is make a link to a page called, lets say, logout.php and add a session_destroy() tag.
Code:
<?php
session_start();
session_destroy();
echo "You are now logged out.";
?>

 

 

 

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: