This is a simple login script. There are only 2 files, and they can be completely customized with any HTML/Javascript you want to make the login look nice and pretty. I typically install these in a new directory, like “admin”. The first file is login.php, which handles the login procedure. The second is user.php which initiates a session for every page and keeps the user logged in. On every page, the first lines should look like this:
include_once("admin/user.php");
if(!$logged)
header('location: admin/login.php');
<?php include_once("user.php"); if($logged){ echo"<strong>Error:</strong> You are already logged in.</p>"; }else{ if(isset($_POST['submit']) && $_POST['submit']=='Go') { $error=validateLogin(stripslashes($_POST['name']),stripslashes($_POST['pass'])); if($error) displayErrors($error); else displayLoggedIn($error); }else displayLogin(); } ?>
<?php session_start(); $username=false; $logged=false; if(isset($_SESSION['logged']) && $_SESSION['logged']==true) { $logged=true; $username=$_SESSION['user']; } function displayLogin(){?> <form action="login.php" method="post"> <div style="width:150px;float:left;">User Name:</div> <div><input type="text" name="name" /></div> <br style="clear:both" /> <div style="width:150px;float:left;">Password:</div> <div><input type="password" name="pass" /></div> <br style="clear:both" /> <input type="submit" name="submit" value="Go" /> </form> <?php } function validateLogin($user,$pass) { $error=false; $con = mysql_connect('localhost','root','');//NEEDS TO BE EDITED if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db('myDatabase',$con);//NEEDS TO BE EDITED $query="SELECT * FROM Users WHERE User='$user'";//NEEDS TO BE EDITED if(@mysql_num_rows(@mysql_query($query))!=1){ $error="User not found."; return $error; } $row=@mysql_fetch_array(@mysql_query($query)); if($row['Pass']!=$pass){ $error="Incorrect password."; return $error; } $_SESSION['logged']=true; return $error; } function displayErrors($error){?> <strong>Error:</strong> <?php echo $error; ?><br /> <form action="login.php" method="post"> <div style="width:150px;float:left;">User Name:</div> <div><input type="text" name="name" /></div> <br style="clear:both" /> <div style="width:150px;float:left;">Password:</div> <div><input type="password" name="pass" /></div> <br style="clear:both" /> <input type="submit" name="submit" value="Go" /> </form> <?php } function displayLoggedIn(){?> You have successfully Logged in! Please wait while you are redirected.<br /> <script type="text/javascript"><!-- setTimeout('Redirect()',3000); function Redirect() { location.href = '../index.php'; } // --></script> <?php } ?>