Php login system with admin features evolt

17,044 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
17,044
On SlideShare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
310
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Php login system with admin features evolt

  1. 1. 3/18/2011 PHP Login System with Admin Feature… Evolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author. PHP Login System with Admin Features P os ted on September 22, 2004 in Code by JP (jpmas ter7 7 ) Introduction I wrote the popular evolt.org tutorial PHP Login Script with Remember Me Feature mainly as an introduction to user sessions and cookies in PHP. Since it was created as a learning tool, many advanced features were left out of the script. By popular demand, I have written and am presenting here a complete Login System, with all the features that were left out of the first script, that can be easily integrated into any website. Notes This article is intended primarily for intermediate to advanced users of PHP, as it is not exactly a tutorial, but a description of the implementation of an advanced Login System. Beginners who are looking to learn about user session and cookies in PHP are advised to read the above mentioned tutorial before reading this article. Features Here are some of the features in this Login System that werent included in the initial tutorial: Better Security - Passwords are not stored in cookies, randomly generated ids take their place. Member Levels - Now users can be differentiated by what level they are (user, admin, etc.) Admin Center - As an admin, you have full control over registered users. You can view user info, upgrade/demote user levels, delete users, delete inactive users, and ban users. Visitor Tracking - You can now tell how many guests and users are actively viewing your site, and who those users are. You also know how many total members your site has. Account Info - Users can now view their own information, and edit it as well. They can also see the information of other users. Form Helper - No more ugly error pages! Now users are redirected to the form they filled out and the errors that have occurred are displayed. Forgot Password - Users who forget their password can have a new one generated for them and sent to their email address. Email - Now emails can be sent to newly registered users. Miscellaneous - Much better code design, smooth page transitions, and MORE! Database All the tables needed for the Login System are written in the file dbtables.sql. You can look at the file and create each table manually or you can just run the file with mysql and it will create all the necessary tables automatically. dbtables.sql # # dbtables.sql # # Simplifies the task of creating all the database tables # used by the login system. # # Can be run from command prompt by typing: # # mysql -u yourusername -D yourdatabasename Code Design I will be presenting the Login System by showing only the important files, describing what they do and how they interact with each other. By reading this constants.php This file will contain all the constants and important information used by the login system. Here you specify stuff like your database username and passwo <? /** * Constants.php * * This file is intended to group all constants to * make it easier for the site administrator to tweak * the login script. *http://www.evolt.org/node/60384 1/25
  2. 2. 3/18/2011 PHP Login System with Admin Feature… * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ /** * Database Constants - these constants are required * in order for there to be a successful connection * to the MySQL database. Make sure the information is * correct. */ define("DB_SERVER", "localhost"); define("DB_USER", "your_name"); define("DB_PASS", "your_pass"); define("DB_NAME", "your_dbname"); /** * Database Table Constants - these constants * hold the names of all the database tables used * in the script. */ define("TBL_USERS", "users"); define("TBL_ACTIVE_USERS", "active_users"); define("TBL_ACTIVE_GUESTS", "active_guests"); define("TBL_BANNED_USERS", "banned_users"); /** * Special Names and Level Constants - the admin * page will only be accessible to the user with * the admin name and also to those users at the * admin user level. Feel free to change the names * and level constants as you see fit, you may * also add additional level specifications. * Levels must be digits between 0-9. */ define("ADMIN_NAME", "admin"); define("GUEST_NAME", "Guest"); define("ADMIN_LEVEL", 9); define("USER_LEVEL", 1); define("GUEST_LEVEL", 0); /** * This boolean constant controls whether or * not the script keeps track of active users * and active guests who are visiting the site. */ define("TRACK_VISITORS", true); /** * Timeout Constants - these constants refer to * the maximum amount of time (in minutes) after * their last page fresh that a user and guest * are still considered active visitors. */ define("USER_TIMEOUT", 10); define("GUEST_TIMEOUT", 5); /** * Cookie Constants - these are the parameters * to the setcookie function call, change them * if necessary to fit your website. If you need * help, visit www.php.net for more info. * <http://www.php.net/manual/en/function.setcookie.php> */ define("COOKIE_EXPIRE", 60*60*24*100); //100 days by default define("COOKIE_PATH", "/"); //Available in whole domain /** * Email Constants - these specify what goes in * the from field in the emails that the script * sends to users, and whether to send a * welcome email to newly registered users. */ define("EMAIL_FROM_NAME", "YourName"); define("EMAIL_FROM_ADDR", "youremail@address.com"); define("EMAIL_WELCOME", false); /** * This constant forces all users to have * lowercase usernames, capital letters are * converted automatically. */ define("ALL_LOWERCASE", false); ?> database.php This file contains all the functions that perform database operations, like adding new users to the database table, verifying username and password, retri <?http://www.evolt.org/node/60384 2/25
  3. 3. 3/18/2011 PHP Login System with Admin Feature… /** * Database.php * * The Database class is meant to simplify the task of accessing * information from the websites database. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 17, 2004 */ include("constants.php"); class MySQLDB { var $connection; //The MySQL database connection var $num_active_users; //Number of active users viewing site var $num_active_guests; //Number of active guests viewing site var $num_members; //Number of signed-up users /* Note: call getNumMembers() to access $num_members! */ /* Class constructor */ function MySQLDB(){ /* Make connection to database */ $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error()); mysql_select_db(DB_NAME, $this->connection) or die(mysql_error()); /** * Only query database to find out number of members * when getNumMembers() is called for the first time, * until then, default value set. */ $this->num_members = -1; if(TRACK_VISITORS){ /* Calculate number of users at site */ $this->calcNumActiveUsers(); /* Calculate number of guests at site */ $this->calcNumActiveGuests(); } } /** * confirmUserPass - Checks whether or not the given * username is in the database, if so it checks if the * given password is the same password in the database * for that user. If the user doesnt exist or if the * passwords dont match up, it returns an error code * (1 or 2). On success it returns 0. */ function confirmUserPass($username, $password){ /* Add slashes if necessary (for query) */ if(!get_magic_quotes_gpc()) { $username = addslashes($username); } /* Verify that user is in database */ $q = "SELECT password FROM ".TBL_USERS." WHERE username = $username"; $result = mysql_query($q, $this->connection); if(!$result || (mysql_numrows($result) < 1)){ return 1; //Indicates username failure } /* Retrieve password from result, strip slashes */ $dbarray = mysql_fetch_array($result); $dbarray[password] = stripslashes($dbarray[password]); $password = stripslashes($password); /* Validate that password is correct */ if($password == $dbarray[password]){ return 0; //Success! Username and password confirmed } else{ return 2; //Indicates password failure } } /** * confirmUserID - Checks whether or not the given * username is in the database, if so it checks if the * given userid is the same userid in the database * for that user. If the user doesnt exist or if the * userids dont match up, it returns an error code * (1 or 2). On success it returns 0. */ function confirmUserID($username, $userid){ /* Add slashes if necessary (for query) */ if(!get_magic_quotes_gpc()) { $username = addslashes($username); } /* Verify that user is in database */ $q = "SELECT userid FROM ".TBL_USERS." WHERE username = $username"; $result = mysql_query($q, $this->connection); if(!$result || (mysql_numrows($result) < 1)){ return 1; //Indicates username failure } /* Retrieve userid from result, strip slashes */http://www.evolt.org/node/60384 3/25
  4. 4. 3/18/2011 PHP Login System with Admin Feature… $dbarray = mysql_fetch_array($result); $dbarray[userid] = stripslashes($dbarray[userid]); $userid = stripslashes($userid); /* Validate that userid is correct */ if($userid == $dbarray[userid]){ return 0; //Success! Username and userid confirmed } else{ return 2; //Indicates userid invalid } } /** * usernameTaken - Returns true if the username has * been taken by another user, false otherwise. */ function usernameTaken($username){ if(!get_magic_quotes_gpc()){ $username = addslashes($username); } $q = "SELECT username FROM ".TBL_USERS." WHERE username = $username"; $result = mysql_query($q, $this->connection); return (mysql_numrows($result) > 0); } /** * usernameBanned - Returns true if the username has * been banned by the administrator. */ function usernameBanned($username){ if(!get_magic_quotes_gpc()){ $username = addslashes($username); } $q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = $username"; $result = mysql_query($q, $this->connection); return (mysql_numrows($result) > 0); } /** * addNewUser - Inserts the given (username, password, email) * info into the database. Appropriate user level is set. * Returns true on success, false otherwise. */ function addNewUser($username, $password, $email){ $time = time(); /* If admin sign up, give admin user level */ if(strcasecmp($username, ADMIN_NAME) == 0){ $ulevel = ADMIN_LEVEL; }else{ $ulevel = USER_LEVEL; } $q = "INSERT INTO ".TBL_USERS." VALUES ($username, $password, 0, $ulevel, $email, $time)"; return mysql_query($q, $this->connection); } /** * updateUserField - Updates a field, specified by the field * parameter, in the users row of the database. */ function updateUserField($username, $field, $value){ $q = "UPDATE ".TBL_USERS." SET ".$field." = $value WHERE username = $username"; return mysql_query($q, $this->connection); } /** * getUserInfo - Returns the result array from a mysql * query asking for all information stored regarding * the given username. If query fails, NULL is returned. */ function getUserInfo($username){ $q = "SELECT * FROM ".TBL_USERS." WHERE username = $username"; $result = mysql_query($q, $this->connection); /* Error occurred, return given name by default */ if(!$result || (mysql_numrows($result) < 1)){ return NULL; } /* Return result array */ $dbarray = mysql_fetch_array($result); return $dbarray; } /** * getNumMembers - Returns the number of signed-up users * of the website, banned members not included. The first * time the function is called on page load, the database * is queried, on subsequent calls, the stored result * is returned. This is to improve efficiency, effectively * not querying the database when no call is made. */ function getNumMembers(){ if($this->num_members < 0){ $q = "SELECT * FROM ".TBL_USERS; $result = mysql_query($q, $this->connection); $this->num_members = mysql_numrows($result); } return $this->num_members; }http://www.evolt.org/node/60384 4/25
  5. 5. 3/18/2011 PHP Login System with Admin Feature… /** * calcNumActiveUsers - Finds out how many active users * are viewing site and sets class variable accordingly. */ function calcNumActiveUsers(){ /* Calculate number of users at site */ $q = "SELECT * FROM ".TBL_ACTIVE_USERS; $result = mysql_query($q, $this->connection); $this->num_active_users = mysql_numrows($result); } /** * calcNumActiveGuests - Finds out how many active guests * are viewing site and sets class variable accordingly. */ function calcNumActiveGuests(){ /* Calculate number of guests at site */ $q = "SELECT * FROM ".TBL_ACTIVE_GUESTS; $result = mysql_query($q, $this->connection); $this->num_active_guests = mysql_numrows($result); } /** * addActiveUser - Updates usernames last active timestamp * in the database, and also adds him to the table of * active users, or updates timestamp if already there. */ function addActiveUser($username, $time){ $q = "UPDATE ".TBL_USERS." SET timestamp = $time WHERE username = $username"; mysql_query($q, $this->connection); if(!TRACK_VISITORS) return; $q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ($username, $time)"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* addActiveGuest - Adds guest to active guests table */ function addActiveGuest($ip, $time){ if(!TRACK_VISITORS) return; $q = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ($ip, $time)"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } /* These functions are self explanatory, no need for comments */ /* removeActiveUser */ function removeActiveUser($username){ if(!TRACK_VISITORS) return; $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = $username"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* removeActiveGuest */ function removeActiveGuest($ip){ if(!TRACK_VISITORS) return; $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = $ip"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } /* removeInactiveUsers */ function removeInactiveUsers(){ if(!TRACK_VISITORS) return; $timeout = time()-USER_TIMEOUT*60; $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* removeInactiveGuests */ function removeInactiveGuests(){ if(!TRACK_VISITORS) return; $timeout = time()-GUEST_TIMEOUT*60; $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } /** * query - Performs the given query on the database and * returns the result, which may be false, true or a * resource identifier. */ function query($query){ return mysql_query($query, $this->connection); } }; /* Create database connection */ $database = new MySQLDB; ?>http://www.evolt.org/node/60384 5/25
  6. 6. 3/18/2011 PHP Login System with Admin Feature… session.php This file is the heart and soul of the Login System. It contains the code to login, logout and register users. It also holds all the information about the <? /** * Session.php * * The Session class is meant to simplify the task of keeping * track of logged in users and also guests. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ include("database.php"); include("mailer.php"); include("form.php"); class Session { var $username; //Username given on sign-up var $userid; //Random value generated on current login var $userlevel; //The level to which the user pertains var $time; //Time user was last active (page loaded) var $logged_in; //True if user is logged in, false otherwise var $userinfo = array(); //The array holding all user info var $url; //The page url current being viewed var $referrer; //Last recorded site page viewed /** * Note: referrer should really only be considered the actual * page referrer in process.php, any other time it may be * inaccurate. */ /* Class constructor */ function Session(){ $this->time = time(); $this->startSession(); } /** * startSession - Performs all the actions necessary to * initialize this session object. Tries to determine if the * the user has logged in already, and sets the variables * accordingly. Also takes advantage of this page load to * update the active visitors tables. */ function startSession(){ global $database; //The database connection session_start(); //Tell PHP to start the session /* Determine if user is logged in */ $this->logged_in = $this->checkLogin(); /** * Set guest value to users not logged in, and update * active guests table accordingly. */ if(!$this->logged_in){ $this->username = $_SESSION[username] = GUEST_NAME; $this->userlevel = GUEST_LEVEL; $database->addActiveGuest($_SERVER[REMOTE_ADDR], $this->time); } /* Update users last active timestamp */ else{ $database->addActiveUser($this->username, $this->time); } /* Remove inactive visitors from database */ $database->removeInactiveUsers(); $database->removeInactiveGuests(); /* Set referrer page */ if(isset($_SESSION[url])){ $this->referrer = $_SESSION[url]; }else{ $this->referrer = "/"; } /* Set current url */ $this->url = $_SESSION[url] = $_SERVER[PHP_SELF]; } /** * checkLogin - Checks if the user has already previously * logged in, and a session with the user has already been * established. Also checks to see if user has been remembered. * If so, the database is queried to make sure of the users * authenticity. Returns true if the user has logged in. */ function checkLogin(){http://www.evolt.org/node/60384 6/25
  7. 7. 3/18/2011 PHP Login System with Admin Feature… global $database; //The database connection /* Check if user has been remembered */ if(isset($_COOKIE[cookname]) && isset($_COOKIE[cookid])){ $this->username = $_SESSION[username] = $_COOKIE[cookname]; $this->userid = $_SESSION[userid] = $_COOKIE[cookid]; } /* Username and userid have been set and not guest */ if(isset($_SESSION[username]) && isset($_SESSION[userid]) && $_SESSION[username] != GUEST_NAME){ /* Confirm that username and userid are valid */ if($database->confirmUserID($_SESSION[username], $_SESSION[userid]) != 0){ /* Variables are incorrect, user not logged in */ unset($_SESSION[username]); unset($_SESSION[userid]); return false; } /* User is logged in, set class variables */ $this->userinfo = $database->getUserInfo($_SESSION[username]); $this->username = $this->userinfo[username]; $this->userid = $this->userinfo[userid]; $this->userlevel = $this->userinfo[userlevel]; return true; } /* User not logged in */ else{ return false; } } /** * login - The user has submitted his username and password * through the login form, this function checks the authenticity * of that information in the database and creates the session. * Effectively logging in the user if all goes well. */ function login($subuser, $subpass, $subremember){ global $database, $form; //The database and form object /* Username error checking */ $field = "user"; //Use field name for username if(!$subuser || strlen($subuser = trim($subuser)) == 0){ $form->setError($field, "* Username not entered"); } else{ /* Check if username is not alphanumeric */ if(!eregi("^([0-9a-z])*$", $subuser)){ $form->setError($field, "* Username not alphanumeric"); } } /* Password error checking */ $field = "pass"; //Use field name for password if(!$subpass){ $form->setError($field, "* Password not entered"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } /* Checks that username is in database and password is correct */ $subuser = stripslashes($subuser); $result = $database->confirmUserPass($subuser, md5($subpass)); /* Check error codes */ if($result == 1){ $field = "user"; $form->setError($field, "* Username not found"); } else if($result == 2){ $field = "pass"; $form->setError($field, "* Invalid password"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } /* Username and password correct, register session variables */ $this->userinfo = $database->getUserInfo($subuser); $this->username = $_SESSION[username] = $this->userinfo[username]; $this->userid = $_SESSION[userid] = $this->generateRandID(); $this->userlevel = $this->userinfo[userlevel]; /* Insert userid into database and update active users table */ $database->updateUserField($this->username, "userid", $this->userid); $database->addActiveUser($this->username, $this->time); $database->removeActiveGuest($_SERVER[REMOTE_ADDR]); /** * This is the cool part: the user has requested that we remember that * hes logged in, so we set two cookies. One to hold his username, * and one to hold his random value userid. It expires by the time * specified in constants.php. Now, next time he comes to our site, we willhttp://www.evolt.org/node/60384 7/25
  8. 8. 3/18/2011 PHP Login System with Admin Feature… * log him in automatically, but only if he didnt log out before he left. */ if($subremember){ setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH); setcookie("cookid", $this->userid, time()+COOKIE_EXPIRE, COOKIE_PATH); } /* Login completed successfully */ return true; } /** * logout - Gets called when the user wants to be logged out of the * website. It deletes any cookies that were stored on the users * computer as a result of him wanting to be remembered, and also * unsets session variables and demotes his user level to guest. */ function logout(){ global $database; //The database connection /** * Delete cookies - the time must be in the past, * so just negate what you added when creating the * cookie. */ if(isset($_COOKIE[cookname]) && isset($_COOKIE[cookid])){ setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH); setcookie("cookid", "", time()-COOKIE_EXPIRE, COOKIE_PATH); } /* Unset PHP session variables */ unset($_SESSION[username]); unset($_SESSION[userid]); /* Reflect fact that user has logged out */ $this->logged_in = false; /** * Remove from active users table and add to * active guests tables. */ $database->removeActiveUser($this->username); $database->addActiveGuest($_SERVER[REMOTE_ADDR], $this->time); /* Set user level to guest */ $this->username = GUEST_NAME; $this->userlevel = GUEST_LEVEL; } /** * register - Gets called when the user has just submitted the * registration form. Determines if there were any errors with * the entry fields, if so, it records the errors and returns * 1. If no errors were found, it registers the new user and * returns 0. Returns 2 if registration failed. */ function register($subuser, $subpass, $subemail){ global $database, $form, $mailer; //The database, form and mailer object /* Username error checking */ $field = "user"; //Use field name for username if(!$subuser || strlen($subuser = trim($subuser)) == 0){ $form->setError($field, "* Username not entered"); } else{ /* Spruce up username, check length */ $subuser = stripslashes($subuser); if(strlen($subuser) < 5){ $form->setError($field, "* Username below 5 characters"); } else if(strlen($subuser) > 30){ $form->setError($field, "* Username above 30 characters"); } /* Check if username is not alphanumeric */ else if(!eregi("^([0-9a-z])+$", $subuser)){ $form->setError($field, "* Username not alphanumeric"); } /* Check if username is reserved */ else if(strcasecmp($subuser, GUEST_NAME) == 0){ $form->setError($field, "* Username reserved word"); } /* Check if username is already in use */ else if($database->usernameTaken($subuser)){ $form->setError($field, "* Username already in use"); } /* Check if username is banned */ else if($database->usernameBanned($subuser)){ $form->setError($field, "* Username banned"); } } /* Password error checking */ $field = "pass"; //Use field name for password if(!$subpass){ $form->setError($field, "* Password not entered"); } else{ /* Spruce up password and check length*/ $subpass = stripslashes($subpass);http://www.evolt.org/node/60384 8/25
  9. 9. 3/18/2011 PHP Login System with Admin Feature… if(strlen($subpass) < 4){ $form->setError($field, "* Password too short"); } /* Check if password is not alphanumeric */ else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){ $form->setError($field, "* Password not alphanumeric"); } /** * Note: I trimmed the password only after I checked the length * because if you fill the password field up with spaces * it looks like a lot more characters than 4, so it looks * kind of stupid to report "password too short". */ } /* Email error checking */ $field = "email"; //Use field name for email if(!$subemail || strlen($subemail = trim($subemail)) == 0){ $form->setError($field, "* Email not entered"); } else{ /* Check if valid email address */ $regex = "^[_+a-z0-9-]+(.[_+a-z0-9-]+)*" ."@[a-z0-9-]+(.[a-z0-9-]{1,})*" .".([a-z]{2,}){1}$"; if(!eregi($regex,$subemail)){ $form->setError($field, "* Email invalid"); } $subemail = stripslashes($subemail); } /* Errors exist, have user correct them */ if($form->num_errors > 0){ return 1; //Errors with form } /* No errors, add the new account to the */ else{ if($database->addNewUser($subuser, md5($subpass), $subemail)){ if(EMAIL_WELCOME){ $mailer->sendWelcome($subuser,$subemail,$subpass); } return 0; //New user added succesfully }else{ return 2; //Registration attempt failed } } } /** * editAccount - Attempts to edit the users account information * including the password, which it first makes sure is correct * if entered, if so and the new password is in the right * format, the change is made. All other fields are changed * automatically. */ function editAccount($subcurpass, $subnewpass, $subemail){ global $database, $form; //The database and form object /* New password entered */ if($subnewpass){ /* Current Password error checking */ $field = "curpass"; //Use field name for current password if(!$subcurpass){ $form->setError($field, "* Current Password not entered"); } else{ /* Check if password too short or is not alphanumeric */ $subcurpass = stripslashes($subcurpass); if(strlen($subcurpass) < 4 || !eregi("^([0-9a-z])+$", ($subcurpass = trim($subcurpass)))){ $form->setError($field, "* Current Password incorrect"); } /* Password entered is incorrect */ if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){ $form->setError($field, "* Current Password incorrect"); } } /* New Password error checking */ $field = "newpass"; //Use field name for new password /* Spruce up password and check length*/ $subpass = stripslashes($subnewpass); if(strlen($subnewpass) < 4){ $form->setError($field, "* New Password too short"); } /* Check if password is not alphanumeric */ else if(!eregi("^([0-9a-z])+$", ($subnewpass = trim($subnewpass)))){ $form->setError($field, "* New Password not alphanumeric"); } } /* Change password attempted */ else if($subcurpass){ /* New Password error reporting */ $field = "newpass"; //Use field name for new password $form->setError($field, "* New Password not entered"); } /* Email error checking */ $field = "email"; //Use field name for emailhttp://www.evolt.org/node/60384 9/25
  10. 10. 3/18/2011 PHP Login System with Admin Feature… if($subemail && strlen($subemail = trim($subemail)) > 0){ /* Check if valid email address */ $regex = "^[_+a-z0-9-]+(.[_+a-z0-9-]+)*" ."@[a-z0-9-]+(.[a-z0-9-]{1,})*" .".([a-z]{2,}){1}$"; if(!eregi($regex,$subemail)){ $form->setError($field, "* Email invalid"); } $subemail = stripslashes($subemail); } /* Errors exist, have user correct them */ if($form->num_errors > 0){ return false; //Errors with form } /* Update password since there were no errors */ if($subcurpass && $subnewpass){ $database->updateUserField($this->username,"password",md5($subnewpass)); } /* Change Email */ if($subemail){ $database->updateUserField($this->username,"email",$subemail); } /* Success! */ return true; } /** * isAdmin - Returns true if currently logged in user is * an administrator, false otherwise. */ function isAdmin(){ return ($this->userlevel == ADMIN_LEVEL || $this->username == ADMIN_NAME); } /** * generateRandID - Generates a string made up of randomized * letters (lower and upper case) and digits and returns * the md5 hash of it to be used as a userid. */ function generateRandID(){ return md5($this->generateRandStr(16)); } /** * generateRandStr - Generates a string made up of randomized * letters (lower and upper case) and digits, the length * is a specified parameter. */ function generateRandStr($length){ $randstr = ""; for($i=0; $i<$length; $i++){ $randnum = mt_rand(0,61); if($randnum < 10){ $randstr .= chr($randnum+48); }else if($randnum < 36){ $randstr .= chr($randnum+55); }else{ $randstr .= chr($randnum+61); } } return $randstr; } }; /** * Initialize session object - This must be initialized before * the form object because the form uses session variables, * which cannot be accessed unless the session has started. */ $session = new Session; /* Initialize form object */ $form = new Form; ?> Read through the code and get a feel for how the script knows when the users are logged in or not (checks cookies and $_SESSION variables). Everything is Forms The creation of a Form class was meant to facilitate the handling of errors with user-submitted forms. It keeps track of what the user entered into the fohttp://www.evolt.org/node/60384 10/25
  11. 11. 3/18/2011 PHP Login System with Admin Feature… form.php <? /** * Form.php * * The Form class is meant to simplify the task of keeping * track of errors in user submitted forms and the form * field values that were entered correctly. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ class Form { var $values = array(); //Holds submitted form field values var $errors = array(); //Holds submitted form error messages var $num_errors; //The number of errors in submitted form /* Class constructor */ function Form(){ /** * Get form value and error arrays, used when there * is an error with a user-submitted form. */ if(isset($_SESSION[value_array]) && isset($_SESSION[error_array])){ $this->values = $_SESSION[value_array]; $this->errors = $_SESSION[error_array]; $this->num_errors = count($this->errors); unset($_SESSION[value_array]); unset($_SESSION[error_array]); } else{ $this->num_errors = 0; } } /** * setValue - Records the value typed into the given * form field by the user. */ function setValue($field, $value){ $this->values[$field] = $value; } /** * setError - Records new form error given the form * field name and the error message attached to it. */ function setError($field, $errmsg){ $this->errors[$field] = $errmsg; $this->num_errors = count($this->errors); } /** * value - Returns the value attached to the given * field, if none exists, the empty string is returned. */ function value($field){ if(array_key_exists($field,$this->values)){ return htmlspecialchars(stripslashes($this->values[$field])); }else{ return ""; } } /** * error - Returns the error message attached to the * given field, if none exists, the empty string is returned. */ function error($field){ if(array_key_exists($field,$this->errors)){ return "<font size="2" color="#ff0000">".$this->errors[$field]."</font>"; }else{ return ""; } } /* getErrorArray - Returns the array of error messages */ function getErrorArray(){ return $this->errors; } }; ?> The $form class object is actually defined at the bottom of session.php, for reasons explained there. Basically how it works is there is a value array andhttp://www.evolt.org/node/60384 11/25
  12. 12. 3/18/2011 PHP Login System with Admin Feature… Look at session.php, login and register functions, they use the form object well and show how to appropriately specify the form errors. Also look later on process.php All forms submitted by the user have to be processed in some way, and this file takes care of that. Every form the user fills out is directed to this page This page is also in charge of re-directing the user to the correct page after the form has been processed, whether it be to the page referrer (default), <? /** * Process.php * * The Process class is meant to simplify the task of processing * user submitted forms, redirecting the user to the correct * pages if errors are found, or if form is successful, either * way. Also handles the logout procedure. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ include("include/session.php"); class Process { /* Class constructor */ function Process(){ global $session; /* User submitted login form */ if(isset($_POST[sublogin])){ $this->procLogin(); } /* User submitted registration form */ else if(isset($_POST[subjoin])){ $this->procRegister(); } /* User submitted forgot password form */ else if(isset($_POST[subforgot])){ $this->procForgotPass(); } /* User submitted edit account form */ else if(isset($_POST[subedit])){ $this->procEditAccount(); } /** * The only other reason user should be directed here * is if he wants to logout, which means user is * logged in currently. */ else if($session->logged_in){ $this->procLogout(); } /** * Should not get here, which means user is viewing this page * by mistake and therefore is redirected. */ else{ header("Location: main.php"); } } /** * procLogin - Processes the user submitted login form, if errors * are found, the user is redirected to correct the information, * if not, the user is effectively logged in to the system. */ function procLogin(){ global $session, $form; /* Login attempt */ $retval = $session->login($_POST[user], $_POST[pass], isset($_POST[remember])); /* Login successful */ if($retval){ header("Location: ".$session->referrer); } /* Login failed */ else{ $_SESSION[value_array] = $_POST; $_SESSION[error_array] = $form->getErrorArray(); header("Location: ".$session->referrer); } } /** * procLogout - Simply attempts to log the user out of the system * given that there is no logout form to process.http://www.evolt.org/node/60384 12/25
  13. 13. 3/18/2011 PHP Login System with Admin Feature… */ function procLogout(){ global $session; $retval = $session->logout(); header("Location: main.php"); } /** * procRegister - Processes the user submitted registration form, * if errors are found, the user is redirected to correct the * information, if not, the user is effectively registered with * the system and an email is (optionally) sent to the newly * created user. */ function procRegister(){ global $session, $form; /* Convert username to all lowercase (by option) */ if(ALL_LOWERCASE){ $_POST[user] = strtolower($_POST[user]); } /* Registration attempt */ $retval = $session->register($_POST[user], $_POST[pass], $_POST[email]); /* Registration Successful */ if($retval == 0){ $_SESSION[reguname] = $_POST[user]; $_SESSION[regsuccess] = true; header("Location: ".$session->referrer); } /* Error found with form */ else if($retval == 1){ $_SESSION[value_array] = $_POST; $_SESSION[error_array] = $form->getErrorArray(); header("Location: ".$session->referrer); } /* Registration attempt failed */ else if($retval == 2){ $_SESSION[reguname] = $_POST[user]; $_SESSION[regsuccess] = false; header("Location: ".$session->referrer); } } /** * procForgotPass - Validates the given username then if * everything is fine, a new password is generated and * emailed to the address the user gave on sign up. */ function procForgotPass(){ global $database, $session, $mailer, $form; /* Username error checking */ $subuser = $_POST[user]; $field = "user"; //Use field name for username if(!$subuser || strlen($subuser = trim($subuser)) == 0){ $form->setError($field, "* Username not entered<br>"); } else{ /* Make sure username is in database */ $subuser = stripslashes($subuser); if(strlen($subuser) < 5 || strlen($subuser) > 30 || !eregi("^([0-9a-z])+$", $subuser) || (!$database->usernameTaken($subuser))){ $form->setError($field, "* Username does not exist<br>"); } } /* Errors exist, have user correct them */ if($form->num_errors > 0){ $_SESSION[value_array] = $_POST; $_SESSION[error_array] = $form->getErrorArray(); } /* Generate new password and email it to user */ else{ /* Generate new password */ $newpass = $session->generateRandStr(8); /* Get email of user */ $usrinf = $database->getUserInfo($subuser); $email = $usrinf[email]; /* Attempt to send the email with new password */ if($mailer->sendNewPass($subuser,$email,$newpass)){ /* Email sent, update database */ $database->updateUserField($subuser, "password", md5($newpass)); $_SESSION[forgotpass] = true; } /* Email failure, do not change password */ else{ $_SESSION[forgotpass] = false; } } header("Location: ".$session->referrer); } /** * procEditAccount - Attempts to edit the users account * information, including the password, which must be verifiedhttp://www.evolt.org/node/60384 13/25
  14. 14. 3/18/2011 PHP Login System with Admin Feature… * before a change is made. */ function procEditAccount(){ global $session, $form; /* Account edit attempt */ $retval = $session->editAccount($_POST[curpass], $_POST[newpass], $_POST[email]); /* Account edit successful */ if($retval){ $_SESSION[useredit] = true; header("Location: ".$session->referrer); } /* Error found with form */ else{ $_SESSION[value_array] = $_POST; $_SESSION[error_array] = $form->getErrorArray(); header("Location: ".$session->referrer); } } }; /* Initialize process */ $process = new Process; ?> Active Visitors Tracking active visitors is accomplished in the following way: There are two database tables, one to hold the active users and one to hold the active gues Associated with the user or guest is a timestamp, this is updated every time he/she loads a page. The timestamp tells us when the user/guest was last acti Admin Center The admin center is the page where admins go to do what they do best, administer the Login System. There they can view the table of users and all the user Admin Name Well, who gets the admin name as a username? You do, but you have to register it, just like any other name. You should do this once you get the script up Adding Admins Lets say you need help with your website, and you want your buddy to help out and be an admin. You can have him register under some username of his choic Main Page The following is an example for your websites main page. It shows a little bit how to use the $session, $form, and $database variables. It contains the l main.php <? /** * Main.php * * This is an example of the main page of a website. Here * users will be able to login. However, like on most sites * the login form doesnt just have to be on the main page, * but re-appear on subsequent pages, depending on whether * the user has logged in or not. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 26, 2004 */ include("include/session.php"); ?> <html> <title>Jpmaster77s Login Script</title> <body> <table> <tr><td>http://www.evolt.org/node/60384 14/25
  15. 15. 3/18/2011 PHP Login System with Admin Feature… <? /** * User has already logged in, so display relevant links, including * a link to the admin center if the user is an administrator. */ if($session->logged_in){ echo "<h1>Logged In</h1>"; echo "Welcome <b>$session->username</b>, you are logged in. <br><br>" ."[<a href="userinfo.php?user=$session->username">My Account</a>] " ."[<a href="useredit.php">Edit Account</a>] "; if($session->isAdmin()){ echo "[<a href="admin/admin.php">Admin Center</a>] "; } echo "[<a href="process.php">Logout</a>]"; } else{ ?> <h1>Login</h1> <? /** * User not logged in, display the login form. * If user has already tried to login, but errors were * found, display the total number of errors. * If errors occurred, they will be displayed. */ if($form->num_errors > 0){ echo "<font size="2" color="#ff0000">".$form->num_errors." error(s) found</font>"; } ?> <form action="process.php" method="POST"> <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr><td>Username:</td><td><input type="text" name="user" maxlength="30" value="<? echo $form->value("user"); ?>"></td><td><? echo $form->error("user"); ? <tr><td>Password:</td><td><input type="password" name="pass" maxlength="30" value="<? echo $form->value("pass"); ?>"></td><td><? echo $form->error("pass" <tr><td colspan="2" align="left"><input type="checkbox" name="remember" <? if($form->value("remember") != ""){ echo "checked"; } ?>> <font size="2">Remember me next time <input type="hidden" name="sublogin" value="1"> <input type="submit" value="Login"></td></tr> <tr><td colspan="2" align="left"><br><font size="2">[<a href="forgotpass.php">Forgot Password?</a>]</font></td><td align="right"></td></tr> <tr><td colspan="2" align="left"><br>Not registered? <a href="register.php">Sign-Up!</a></td></tr> </table> </form> <? } /** * Just a little page footer, tells how many registered members * there are, how many users currently logged in and viewing site, * and how many guests viewing site. Active users are displayed, * with link to their user information. */ echo "</td></tr><tr><td align="center"><br><br>"; echo "<b>Member Total:</b> ".$database->getNumMembers()."<br>"; echo "There are $database->num_active_users registered members and "; echo "$database->num_active_guests guests viewing the site.<br><br>"; include("include/view_active.php"); ?> </td></tr> </table> </body> </html> Download As youve probably noticed, pages have been left out of the article. Wheres the Admin Center? User Account Page? Forgot Password Form? ... Well, theres PHP Login System v.2.0 (zip file 23KB) Conclusion The only reason I made this advanced Login System was because so many people liked my first one and wanted to see more features get added. So I decided to Attachment Size Login_System_v.2.0.zip 22.83 KBhttp://www.evolt.org/node/60384 15/25
  16. 16. 3/18/2011 PHP Login System with Admin Feature…well written step-by-stepSubmitted by spinhead on September 28, 2004 - 06:53.Im still refining my PHP, and this article is a real boost. Makes me feel like even I can do this!login or register to post commentsAnd he does it again !Submitted by saruman on September 28, 2004 - 12:51.Thanks again JP, You truly are great for taking your time to do these scripts, I did manage to get the last one working but have not really had time to finish the site I was supposed to use itwith, maybe ill try upgrade to this one :)I will try it out when I get a chance and let you knowlogin or register to post commentsQuestionSubmitted by libelle on September 28, 2004 - 16:09.When I look at the PEAR libraries, I see a fair amount of infrastructure for this kind of application. Any recommendations with regard to using them? Im interested in the more generalcharacter (e.g., DB-agnosticism) of those libraries, but like the additional features you implement.login or register to post commentsReal cool scriptSubmitted by wocktu on September 28, 2004 - 16:37.By scripts work really great. Especially this one. I havnt tried to modify the registration page yet so touch wood I wont stuff it up. Im doing a Degree in IT and am building a Squash clubswebsite with a court booking system, this will help out greatly. Thanks JPlogin or register to post commentsGreatSubmitted by domostick on September 28, 2004 - 18:36.On the other script you could hide html from people that were not logged in. The old php{>^^Did not work. It looks something like that lol. Is there a way to do this again?login or register to post commentsCustomizing Main.phpSubmitted by swattle on September 29, 2004 - 14:35.I am new to PHP and I am starting a new website and at swattle.com . I am not sure what I am doing wrong. If you visit http://swattle.com you will see my site. You can login by creatingyourself your own account or use the one I have been fooling around with which is user name: testing password: 12345 You will not that when you login at http://www.swattle.com/index.phpyou will be redirected to http://www.swattle.com/usr/main.php This is the folder I placed all of the files from the archive I downloaded to. Why does it redirect you to the main.php file? I wantit to redirect back to http://www.swattle.com/index.php Where is the script getting this url location from?login or register to post commentsreplySubmitted by domostick on September 29, 2004 - 15:45.you must change the redirect link in the file you placed the login box.also anybody know of the new php code to hide html from non logged in users. i tried the old one, it dont worklogin or register to post commentsCustomizing LoginSubmitted by swattle on September 29, 2004 - 17:00.I am not sure where you mean. The login box in my main index.php page and there is no variable listed for a redirect. The only place I see is a redirect in the process.php file which is the lastattempt of logic in the else if statement to determine what the users is doing with a form.login or register to post commentshttp://www.evolt.org/node/60384 16/25
  17. 17. 3/18/2011 PHP Login System with Admin Feature…Process.php and $session objectSubmitted by jpmaster77 on September 29, 2004 - 17:14.swattle,In the HTML login form at swattle.com/index.php you called it "sublogin2", (it is called "sublogin" in the code provided), so Im assuming you are checking for this name inswattle.com/usr/process.php. Because if you arent, which I dont think you are, it will redirect to main.php. You need to edit process.php to check for this form name, then log the user in andredirect to either $session->referrer or just type in "../index.php".domostick,There is no global $logged_in variable like in the last script. This new script is more object oriented, you want the $session->logged_in variable.Example: if($session->logged_in){<br> &nbsp;&nbsp;echo "Hey $session->username, you are logged in!";<br> }<br> else{<br> &nbsp;&nbsp;echo "You are not logged in.";<br> }Note that this example is seen in main.php.Good luck,JPlogin or register to post commentssubloginSubmitted by swattle on September 29, 2004 - 18:38.JP, That was the problem. I am so silly. I must have looked at that string of characters 3,000 times and never paid any attention to the 2 One other thing, Maybe because of how I customizedthe form to login, but now when you log in, the form stays AND it displays welcome back, username. How can I get it so the login form is no longer shown after the user logs in? My plan is tocreate a top header on my finished site which will give the visitor the option to enter his user name and pass right from index.php Thanks, C hadlogin or register to post commentssublogin Part 2Submitted by swattle on September 29, 2004 - 19:06.If it is any help I posted the actual source, including all php references in my index file. You can view it at http://www.swattle.com/index2.txtlogin or register to post commentsWhat else?Submitted by jpmaster77 on September 29, 2004 - 20:01.swattle,Your code displays welcome back and then the form because you dont have an else statement. It should be: if($session->logged_in){<br> &nbsp;&nbsp;...<br> } else{<br> &nbsp;&nbsp;...<br> }So to fix it, add the else statement. It is in the original main.php, so be careful when you edit stuff or just copy and paste code, you might forget something.JPlogin or register to post commentsPublic Domain?Submitted by fu_fish on September 30, 2004 - 05:35.Are these scripts released to the public domain for use by anyone, anywhere? Theyre a whole lot better implemented than my current login system.login or register to post commentshttp://www.evolt.org/node/60384 17/25
  18. 18. 3/18/2011 PHP Login System with Admin Feature…Sure you canSubmitted by jpmaster77 on September 30, 2004 - 07:16.fu_fish,I wrote this Login System for everyone for use on anything. If you would like to use it, please DO, because thats the whole purpose of it.Thanks for checking it out,JPlogin or register to post commentsreplySubmitted by domostick on September 30, 2004 - 14:08.sorry but i didnt get it, no exlanation of where it goes lol. just comes up with an errorlogin or register to post commentsjpmaster77Submitted by dirtboy on September 30, 2004 - 18:56.The Grandmaster of C ++ has struck again.................................awesome script.Thanks,login or register to post commentsreplySubmitted by domostick on October 1, 2004 - 13:39.hey dirtboy sorry about that night, just angry from school and stuff. can you help me where the php coding goes to hide the html of people who arent logged in?login or register to post commentsmain.phpSubmitted by jpmaster77 on October 1, 2004 - 16:57.domostick,I dont get what the problem youre having is. If you look at main.php, it checks whether or not the user is logged in, if so it displays the HTML for logged in users (basically links to relevantpages), if not it displays the login form.What more are you looking for? For a general protected page, for users who are logged in you display the protected page HTML, for users who are not logged in you display an error message.This can be done with an if-else, and the variable you are checking is $session->logged_in , which can be used when session.php is included.Let me know if this solves your problem,JPlogin or register to post commentsHey jpmaster77Submitted by Glytch on October 2, 2004 - 01:26.Im a newbie to PHP and so far this has been great (the script) and very easy to setup, but I was wondering how to change the URL after successfully logging in, or including more in main.phpafter logging in. I tried what you were talking to swattle about, just replacing $session->referrer with a URL but it didnt work, or is that not what I was supposed to do? Any help would bemuch appreciated. C heers, Glytchlogin or register to post commentsreplSubmitted by domostick on October 2, 2004 - 08:08.Thanks for trying to help me jp, but I see in the first session the else statment to put my html. But where do I place it? Before or after }else{I tried both but they both come up with an errorlogin or register to post commentsdomostickSubmitted by dirtboy on October 2, 2004 - 08:54.My friend open up main.php and just look and read the code.Do you see the line that sayshttp://www.evolt.org/node/60384 18/25
  19. 19. 3/18/2011 PHP Login System with Admin Feature… if($session->logged_in){ echo "Logged In"; echo "Welcome $session->username, you are logged in. " ."[username">My Account] " ."[Edit Account] "; if($session->isAdmin()){ echo "[Admin Center] "; } echo "[Logout]";What that code does is it checks to see if the user is logged in and Grandmaster of C ++ has added if they are logged in are they a user or admin. Then the rest of the code after}else{displays the message to non logged in users"which is why it displays the login box form"login or register to post commentsdomostickSubmitted by dirtboy on October 2, 2004 - 08:56.You place what message you want logged in users to see before the }else{ statement and what you want non logged in users to see after the }else{ statement.login or register to post commentsreplySubmitted by domostick on October 2, 2004 - 17:27.like i said before any way i place it, it comes up with a parse code error on line 74.login or register to post commentsdomostickSubmitted by dirtboy on October 2, 2004 - 17:44.why dont you post your code so we can see it ?login or register to post commentsreplySubmitted by domostick on October 2, 2004 - 18:21.got it to work but now i cant logout. You click logout but it just reloads the page and doesnt log out.login or register to post commentsdomostickSubmitted by dirtboy on October 2, 2004 - 18:48.I do not know what you have done to the code for that error ..........But I do know there is nothing wrong with this script straight out of the zip filelogin or register to post commentsExplainSubmitted by jpmaster77 on October 2, 2004 - 23:02.Glytch,Are you still having a problem? Whats the problem exactly. If you want to redirect the user to some specific page after they log in, you need to modify process.php. Find the function where itprocesses the login form, then modify the header call. By default it is: if($retval){<br> &nbsp;&nbsp;header("Location: ".$session->referrer);<br> }But you can hard code a specific page for it to go to by changing it to:http://www.evolt.org/node/60384 19/25
  20. 20. 3/18/2011 PHP Login System with Admin Feature… if($retval){<br> &nbsp;&nbsp;header("Location: somepage.php");<br> }Hope this helps,JPlogin or register to post commentsHELP!Submitted by jaimeharvey on October 3, 2004 - 13:59.Hi all,Fantastic script - I am trying to get my head round most of it, but it works like a charm "out the box"!Really fundamental question here - how do you add other fields like email etc??Here is what I have tried so far... (only code shown is code that I have changed). Every time I click the register button, it gives me the registration failed pageThanks in advance!register.php and process.php below that <?php <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr><td>Username:</td><td>value("user"); ?>">error("user"); ?> Password:value("pass"); ?>">error("pass"); ?> Email:value("email"); ?>">error("email"); ?> ?>process.php <?php function procLogin(){ global $session, $form; /* Login attempt */ $retval = $session->login($_POST[user], $_POST[pass], $_POST[email], isset($_POST[remember])); /* Login successful */ if($retval){ header("Location: ".$session->referrer); } /* Login failed */ else{ $_SESSION[value_array] = $_POST; $_SESSION[error_array] = $form->getErrorArray(); header("Location: ".$session->referrer); } } ?>login or register to post commentsStupid meSubmitted by jaimeharvey on October 3, 2004 - 14:09.ok - FORGET EVERYTHING I JUST SAIDJust got totally confused - very sorry!!!login or register to post commentsUser Account EditSubmitted by peterc on October 4, 2004 - 03:30.Excellent script, JP. Thank you. While working through it I have picked up this problem. When useredit.php opens, it shows empty curpass and newpass fields with the email of the logged onuser displayed. Without entering anything, if I click the Edit Account button, I am advised that the account has been successfully updated. Shouldnt it advise me that both password fields areempty? When something is entered in either field, it seems to work OK.login or register to post commentsAccount EditSubmitted by jpmaster77 on October 4, 2004 - 08:10.http://www.evolt.org/node/60384 20/25
  21. 21. 3/18/2011 PHP Login System with Admin Feature…peterc,What if you want to just modify your email address and you dont want to change your password? Thats how the account edit page works, if something is entered into either password field, itassumes you want to change your password, so it does error checking on those two fields. However, if you dont enter anything in either of the two fields, it assumes you dont want to changeyour password, just your email.JPlogin or register to post commentsProtecting PagesSubmitted by jaimeharvey on October 4, 2004 - 11:13.Hi guys, What is the code needed at the top of new pages (that I have created - not in the download) in order to protect them - i.e. only allow access to users that have logged in? Thankslogin or register to post commentsAccount EditSubmitted by peterc on October 4, 2004 - 12:35.JP Yes, I get it. Many thanks again - really good script. Peterlogin or register to post commentsProtected PageSubmitted by jpmaster77 on October 4, 2004 - 14:46.jaimeharvey,To make protected pages you want to use the $session->logged_in variable, but make sure session.php is included before you try and use it, or else it will give you an error.Example: protected.php <? include("include/session.php"); if($session->logged_in){ echo "You are viewing the protected page"; } else{ echo "You are not allowed to view this page"; } ?>Make sure the included path to session.php is correct in the page you actually want to protect, and you can insert HTML code into the if statement to actually display the page and not just amessage.Hope this helps,JPlogin or register to post commentsThanksSubmitted by jaimeharvey on October 5, 2004 - 09:11.Thats great - thanks very much!Ever considered a job in customer service!!login or register to post commentsMore questions!Submitted by jaimeharvey on October 5, 2004 - 14:55.Having spent more time working on these pages I have noticed 2 things: 1. The question I asked earlier was really very stupid (!) and 2 how logically they have been put togther!One question though, I have modified the database with other fields etc, and what I have done is on the admin page I have added a link on the users table to go the the userinfo.php pageabout that user (which works fine).However, earlier I had modified that page (userinfo) so that anyone other than the user whos details they were could not access the page (see code). Is there anyway to change the IFstatment to IF(session username OR admin)???Thanks, Jamiehttp://www.evolt.org/node/60384 21/25
  22. 22. 3/18/2011 PHP Login System with Admin Feature… <?php <? /* Requested Username error checking */ $req_user = trim($_GET[user]); if(!$req_user || strlen($req_user) == 0 || !eregi("^([0-9a-z])+$", $req_user) || !$database->usernameTaken($req_user)){ die("Username not registered"); } /* Logged in user viewing own account */ if(strcmp($session->username,$req_user) == 0){ echo "My Account"; } /* Visitor not viewing own account */ else{ echo "You are not authorised to view this information"; } /* Display requested user information */ $req_user_info = $database->getUserInfo($req_user); /* Usename */ if(strcmp($session->username,$req_user) == 0){ echo "<b>Username: </b>".$req_user_info[username]."<br>"; echo "<b>Email: </b>".$req_user_info[email]."<br>"; echo "<b>Title: </b>".$req_user_info[title]."<br>"; echo "<b>Forename: </b>".$req_user_info[forename]."<br>"; echo "<b>Surname: </b>".$req_user_info[surname]."<br>"; echo "<b>Address 1: </b>".$req_user_info[address1]."<br>"; echo "<b>Address 2: </b>".$req_user_info[address2]."<br>"; echo "<b>City: </b>".$req_user_info[city]."<br>"; echo "<b>County: </b>".$req_user_info[county]."<br>"; echo "<b>Postcode: </b>".$req_user_info[postcode]."<br>"; echo "<b>Phone number: </b>".$req_user_info[telephone]."<br>"; echo "<b>Mobile number: </b>".$req_user_info[mobilephone]."<br>"; } ?>login or register to post commentsGreat ScriptSubmitted by paulo61 on October 5, 2004 - 14:57.This is a great scrip - works out of the box and easy to customise and maintain. I have a question about the logout logic. It seems that when a user los out they are demoted to guest leveland guests expire after 5 minutes by default. Is there anyway to have logouts take affect immediatly, could I define GUEST_TIMEOUT as 0 for example. The best thing about this code is thesupporting documentation - paul.....login or register to post commentsMore AnswersSubmitted by jpmaster77 on October 5, 2004 - 20:49.jaimeharvey,You want to use the $session->isAdmin() function, it returns true if the user that is logged in has admin priviledges. if(strcmp($session->username,$req_user) == 0 || $session->isAdmin()){ echo "You are allowed to view this page"; }paulo61,I would not recommend setting GUEST_TIMEOUT to 0, because then your site will never know when guests are viewing the site. You could of course decrease it to 1 perhaps, if you think 5 istoo much. What I would suggest you do is remove one line from the logout() function in session.php, the one that adds the user that just logged out to the active guests table. So find andremove or comment out this line:http://www.evolt.org/node/60384 22/25
  23. 23. 3/18/2011 PHP Login System with Admin Feature… $database->addActiveGuest($_SERVER[REMOTE_ADDR], $this->time);Its near the end of the logout() function.Hope this helps,JPlogin or register to post commentsHELP.Submitted by deppie on October 6, 2004 - 12:36.x__X http://rebel.urban-ducks.net ...All thats on line 14 is a "{" ... Please help. Sorry- Im kinda new to PHP.. -Raelogin or register to post commentsProtected pagesSubmitted by Brewman on October 6, 2004 - 13:52.JP .... in the Protected page comment ... you mentioned "you can insert HTML code into the if statement to actually display the page and not just a message." C ould you please show anexample of how to insert the HTML correctly. Ive tried various ways ... Im new to PHP and Im sure Im missing the correct coding. I placed the HTML code inside the quote marks after theecho statement.login or register to post commentsHelp and Protected HTMLSubmitted by jpmaster77 on October 6, 2004 - 15:50.deppie,It tells me youre getting an error when trying to connect to your database, "Access denied", make sure your database name and password information is specified correctly in constants.php.If you still cant connect after verifying the information, then ask your web host what you need to put in.Brewman,To insert HTML code directly into a php file, you need to close the php tag (insert "?>"). And then open the php tag when you want to use php again (insert "<?").Example: protected.php <? include("include/session.php"); ?> Protected Page <? /* User is not logged in */ if(!$session->logged_in){ ?> Insert HTML code here that says "You are not allowed to view this page" <? } /* User is logged in */ else{ ?> Insert HTML code here that says "This is the protected page" <? } ?>Notice that I switched it up in the example, such that the first "if" clause checks if the user is NOT logged in, the reason is most of the time the HTML code that goes in the "if" statement is a lotshorter than the code that goes in the "else".JPlogin or register to post commentshttp://www.evolt.org/node/60384 23/25
  24. 24. 3/18/2011 PHP Login System with Admin Feature…Protected 2Submitted by jpmaster77 on October 6, 2004 - 15:57.Brewman,Sorry the code I gave you was suppose to include HTML tags and they didnt show up, heres what I wanted to show:Example: protected.php <? include("include/session.php"); ?> <html> <title>Protected Page</title> <? /* User is not logged in */ if(!$session->logged_in){ ?> <body> Insert HTML code here that says "You are not allowed to view this page" </body> <? } /* User is logged in */ else{ ?> <body> Insert HTML code here that says "This is the protected page" </body> <? } ?> </html>JPlogin or register to post commentsThanks so much!Submitted by Brewman on October 6, 2004 - 16:29.JP ... your awesome! The script is now running flawlessly. Thanks so much for your help.By the way, this script is the best php login script on the web.login or register to post commentsWell Script.Submitted by sathiyan_lee on October 6, 2004 - 23:01.This is really a fanatastic scripts I have ever seen. It looks very simple to undestand. Lot of thanks to you JPlogin or register to post commentsI always get the "Username below 5 characters"Submitted by robmorin on October 8, 2004 - 06:44.No matter how many i type?? Any suggestions? When i go to register... for the first time Thanks Roblogin or register to post commentsExcellent scripts but...Submitted by gonzalezamado on October 8, 2004 - 08:05.I am new with PHP and these scripts look like what I was looking for. But my actual case scenario is quite special. I am unable to access any DBMS from my ISP, so I will need to implement itusing a flat file "database" system. Is it possible? What should be adapted to accomplish that approach? JP, thank you in advance for all the help you can providelogin or register to post commentsFlat file databaseSubmitted by jpmaster77 on October 8, 2004 - 11:26.http://www.evolt.org/node/60384 24/25
  25. 25. 3/18/2011 PHP Login System with Admin Feature…gonzalezamado,I initially was going to write a flat file database for this Login System, specifically for people in your position, but I quickly realized that all the features I wanted (tracking active visitors, etc.)could not really be achieved, or at least to the level that I wanted them to, with a flat-file database. They dont scale to large number of users and you cant write to the same file at the sametime, so that basically means a huge performance decline. But, those are the drawbacks of flat file databases, and you cant do anything about that.You have two options, the first is to write a simple flat file database that doesnt support tracking active visitors (just stores user information and looks it up). This would take some time to getright, but it shouldnt be that hard. The other is to find a pre-existing flat file database on the web that you can just insert for use on your website. I found this one while searching google:FFDB. Its pretty advanced so you may get the active visitors thing working. So just think about that, and Im sorry I dont have code to give you that Ive written.robmorin,Im not sure I understand the problem youre having, it works when you register but just not on the first time you load the page? It gives you that error. Look at register() function insession.php, thats where it checks the length of the string you entered. However it trims the string and calls stripslashes() on it before it checks the length. Id suggest you echo the string itschecking for debugging this problem. I dont know why it wouldnt work on the first try, but on subsequent tries it does.login or register to post commentsUsing list boxes - How?Submitted by SunC oder on October 10, 2004 - 03:24.Hi, C urrently, the register/main php scripts are using text boxes, such as: value("pass"); ?>"> for example. But how to use the php code within a list box, such as: Germany USA UK Howexactly must the php code look alike in that listbox? Please let me know. I tried several possibilities but none seemed to work. Otherwise, the login script is great, it worked out of the box.Unlike the previous one which does not performed redirection on one of my pcs using IE (but was ok with NS), for whatever reasons, but worked on other pcs and configurations including IEfrom me. Never figured out why exactly it had problems with IE. Thanks JP for developing and sharing the new code with uslogin or register to post commentsUsing list boxes - How? (II)Submitted by SunC oder on October 10, 2004 - 03:31.Sorry, the text above looks a little bit confusing, not exactly what i have expected after the preview. I should however be clear what I mean: How must the complete list box (including phpcode) look alike. A small sample would be much appreciated. Thanks.login or register to post commentsList boxesSubmitted by jpmaster77 on October 10, 2004 - 17:05.SunC oder,Youd have to check every list item and see if the value given by the list name is equal to the list item value, if so, you print out "selected" inside the option tag. Thats what tells the HTMLwhich item is selected.Example: <SELECT NAME="country" SIZE=3> <OPTION VALUE="Germany" <? if($form->value("country") == "Germany"){ echo "selected"; } ?>>Germany <OPTION VALUE="USA" <? if($form->value("country") == "USA"){ echo "selected"; } ?>>USA <OPTION VALUE="UK" <? if($form->value("country") == "UK"){ echo "selected"; } ?>>UK </SELECT>Hope this helps,JPlogin or register to post comments 1 2 3 4 5 6 7 8 9 ... next page last pagehttp://www.evolt.org/node/60384 25/25

×