How to restrict users from entering a page without being logged on

Jahed picture Jahed · Oct 26, 2011 · Viewed 13.3k times · Source

i used sessions to log a user in so basically the user is stored in a session. what code do i use to stick into my following file so a user cannot access the page unless he/she is logged in.

    <?php
session_start();

?>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cook It Dot Com</title>
<link href="../style.css" rel="stylesheet" type="text/css" />
</head>
<body><div id="wrap">
<div id="header"></div>
<div id="nav">
            <ul id='menu'>
             <li><a href="../usersloggedin/starters.php" >Starters</a></li>
            <li><a href="../usersloggedin/mains.php" >Mains</a></li>
            <li><a href="../usersloggedin/vegeterian.php" >Vegeterian</a></li>
            <li><a href="../usersloggedin/desserts.php">Desserts</a></li>
            </ul>

            <ul id="rightmenu">
           <li> <a href="logout.php">Logout</a></li>

            </ul>


</div>


<div id="content">
  <div id="info" align="justify"><FONT COLOR="white">
   My Account - 
<?php
session_start();
require_once '../database.php';
if (isset($_SESSION['myusername'])){
echo "Welcome ".$_SESSION['myusername'];
}
?>
<hr />
<br /> Upload Your Recipes<br /><br />

<a href="../upload/uploadstarter.php">Upload Starter</a>
<a href="../upload/uploadmains.php">Upload Mains</a>
<a href="../upload/uploadvegeterian.php">Upload Vegeterian</a>
<a href="../upload/uploaddessert.php">Upload Desserts</a>

<br /><br />Edit/Delete Your Recipes<br/><br/>

<a href="../editdelete/editstarters.php">Starter</a>
<a href="../editdelete/editmains.php">Mains</a>
<a href="../editdelete/editvegeterian.php">Vegeterian</a>
<a href="../editdelete/editdesserts.php">Desserts</a>



</div></div>
<div id="footer"><div id="footerinfo" align="center">Copyright Cook It Dot Com 2011 - Designed By Jahedul Hussain - </a></div></div>
</div>
</body>
</html>

Thanks A LOT!

Answer

Ash Burlaczenko picture Ash Burlaczenko · Oct 26, 2011

How about something like

if(!isset($_SESSION["user"]))
{
    header("Location: homepage.php");
}

Basically, if there is not a user session redirect to the homepage.