PHP Session technique is used to control menu navigation i.e user can only access the page after Sign in. Other wise user can click the link but using session technology that page can redirected.
Session Introduction: Session is a one of the PHP Variable. It stores the user providing information for further user manipulations. When user sign in website to store all available or required information is stored in temporary and deleted after sign out the user.
basic syntax:
This code is inserted within the head tag
<?php
session_start(); // this code is used to start the session
$_SESSION['counts']=1; // this code is used to store the user values name
?>
This code is inserted within body tag
<?php
echo "Pageviews=". $_SESSION['views']; // Printing the Session variable
?>
PHP Session Using Menu control: To create one header file and we can create required link pages.
i.e home page, service page, contact us page and log out or log in pages.
First Header File:
Code:
<table>
<tr>
<td>
<a href="index.php">Home</a>
</td>
<td>
<a href="about.php">About Us</a>
</td>
<td>
<a href="services.php">Services</a>
</td>
<td>
<a href="contacus.php">Contact Us</a>
</td>
<?php
if(isset($_SESSION['username'])) // check the user already sign in or not
{
?>
<td>
<a href="logout.php">Logout</a> // this link is only show if the user sign in
</td>
<?php
}
?>
</tr>
</table>
Link Pages:
This code is main for all link pages this code is inserted within head tag. but Body tag can contain different element depends upon the pages
ex: home page, service page, contact us page and logout or login page
Code:
<?php
session_start(); // start the session
if(!isset($_SESSION['username'])) // check the user sign in or not
{
$url="index.php"; // storing target page to variable
redirect($url); // redirect function is to redirect to the specified location
}
?>
The function is created and stored in separate file and included required pages
Code:
<?php
function redirect($targetPage)
{
if (!headers_sent())
{
header("location:".$targetPage);
}
else
{
?>
<script language="javascript">
window.location.href="<?php echo $targetPage;?>"; // javascript redirecting specified file location
</script>
<?php
}
}
?>