This Snippet will check and see if if a user is logged in or not. functions.php <?php function loggedIn(){ //Session logged is set if the user is logged in //set it on 1 if the user has successfully logged in //if it wasn't set create a login form if(!$_SESSION['loggd']){ echo'<form action="checkLogin.php" method="post"> <p> Username:<br> <input type="text" name="username"> </p> <p> Password:<br> <input type="password" name="username"> </p> <p> <input type="submit" name="submit" value="Log In"> </p> </form>'; //if session is equal to 1, display //Welcome, and whaterver their user name is }else{ echo 'Welcome, '.$_SESSION['username']; } } ?> PHP: index.php <?php //Start the session session_start(); //This is a simplified HTML Document ?> <html> <head> <title>My Page</title> </head> <body> <?php //Call the functions file require_once("functions.php"); //Display either the user's name, or the login form //This can be placed on many pages without having //to re-write the form everytime, just use this function logedIn(); ?> </body> </html> PHP:
Although this will work, it isn't ideal since you login check should come before any html is output. Something like this: index.php <?php // define whether this page requires login define('SECURE_PAGE', true); // include session handler include_once('session.inc.php'); ?> <html> <head> <title>My Secure Page</title> </head> <body> SECURE CONTENT OF SOME SORT </body> </html> PHP: session.inc.php <?php // start session session_start(); // is login required on this page if((defined('SECURE_PAGE')) && (SECURE_PAGE == true)) { // if the user logged in if($_SESSION['loggedIn'] != true) { // not logged in, redirect to login page header('location: login.php'); exit; } } ?> PHP: login.php <?php // include session handler include_once('session.inc.php'); // check login against your database here when the form is submitted if(isset($_REQUEST['username'])) { // check username/password in db here (specific to your setup) // if valid login, set session and redirect to the secure index page $_SESSION['loggedIn'] = true; $_SESSION['username'] = $_REQUEST['username']; header('location: index.php'); exit; } ?> <html> <head> <title>My Login Page</title> </head> <body> <form action="login.php" method="post"> <p> Username:<br/> <input type="text" name="username"/> </p> <p> Password:<br/> <input type="password" name="username"/> </p> <p> <input type="submit" name="submit" value="Log In"/> </p> </form> </body> </html> PHP: From then on all your need to add to require login on any page is this to the top: <?php // define whether this page requires login define('SECURE_PAGE', true); // include session checker include_once('session.inc.php'); ?> PHP: