TRemmie Posted September 15, 2009 Share Posted September 15, 2009 Hi, i am working on a project that will have a login feature connected to a SQL database. I have that all figured out except the "login form" will be on each page of the website, where as most tutorials/code I have found is based around having one main login page, and if the login is successfull it redirects to that page with header("Location: www.page.com/login.php") type of workaround. The problem I am having is since they will be able to login on any page, I need to redirect to the specific page they logged in from. I am a total newbie when it comes to code, so be gentle, but I am working with something like the following: <?php // Connects to your Database mysql_connect("111111111111", "2222222222222", "33333333333") or die(mysql_error()); mysql_select_db("444444444444") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])) //if there is, it logs you in and directes you to the members page { $username = $_COOKIE['ID_my_site']; $pass = $_COOKIE['Key_my_site']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); while($info = mysql_fetch_array( $check )) { if ($pass != $info['password']) { } else { header("Location: index.php"); } } } // makes sure they filled it in if(!$_POST['username'] | !$_POST['pass']) { die('You did not fill in a required field.'); } // checks it against the database if (!get_magic_quotes_gpc()) { $_POST['email'] = addslashes($_POST['email']); } $check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error()); //Gives error if user dosen't exist $check2 = mysql_num_rows($check); if ($check2 == 0) { die('That user does not exist in our database. <a href=add.php>Click Here to Register</a>'); } while($info = mysql_fetch_array( $check )) { $_POST['pass'] = stripslashes($_POST['pass']); $info['password'] = stripslashes($info['password']); $_POST['pass'] = md5($_POST['pass']); //gives error if the password is wrong if ($_POST['pass'] != $info['password']) { die('Incorrect password, please try again.'); } else { // if login is ok then we add a cookie $_POST['username'] = stripslashes($_POST['username']); $hour = time() + 3600; setcookie(ID_my_site, $_POST['username'], $hour); setcookie(Key_my_site, $_POST['pass'], $hour); //then redirect them to the members area header("Location: index.php"); } } // if they are not logged in ?> Link to comment https://forums.phpfreaks.com/topic/174393-having-a-login-script-that-doesnt-redirect-to-a-page/ Share on other sites More sharing options...
PFMaBiSmAd Posted September 16, 2009 Share Posted September 16, 2009 I need to redirect to the specific page they logged in from. No. You don't. What you need to do is build a login "module" that you can place (include/create an instance a class) anywhere on any page. The code that makes up this "module" displays the login in form if you are not logged in or it displays something like the logged in username and a log out link if you are logged in. The login form just submits to the current page (an empty action="" attribute will work.) You should be able to search the Internet for a login script that functions this way to use as an example of how you would do it. Link to comment https://forums.phpfreaks.com/topic/174393-having-a-login-script-that-doesnt-redirect-to-a-page/#findComment-919239 Share on other sites More sharing options...
TRemmie Posted September 16, 2009 Author Share Posted September 16, 2009 Even if I use a form based around a if statement that will check if they are logged in, and if they arent will display the login form, and if they are, will display a "Welcome" message, I still am having trouble with how the user is able to login, especially if the submit form has an empty action="". I googled for over an hour but couldnt find anyone who doesnt use a php login system based around a form that submits to a "logincheck.php" type of file and if the users information is in the database, redirects using header location. Like I said I am pretty new to this but I am determined to figure this out. (With the help of some veterans ) Link to comment https://forums.phpfreaks.com/topic/174393-having-a-login-script-that-doesnt-redirect-to-a-page/#findComment-919651 Share on other sites More sharing options...
Batosi Posted September 16, 2009 Share Posted September 16, 2009 Well why dont you just combine both methods. Have your login possible on any page which sends you to logincheck.php, but record the last page visited in a session variable so once they login they will be redirected to that page again. Link to comment https://forums.phpfreaks.com/topic/174393-having-a-login-script-that-doesnt-redirect-to-a-page/#findComment-919683 Share on other sites More sharing options...
PFMaBiSmAd Posted September 16, 2009 Share Posted September 16, 2009 Your page, any page - <?php session_start(); // load any class definition files - function __autoload($class_name) { require_once $class_name . '.php'; } // Using a login class - $user = new login_class(); // create instance of class echo '<p>'; $user->login_box(); // place login in box here, displays the login form or the logged in information/logout link echo '</p>'; // At this point you are either a non-logged in guest on this page or you are logged in. // The following demonstrates the use of the class functions on the page - if($user->logged_in()){ echo "Content that the logged in user: {$user->user_name()}, would see on this page...<br />"; } else { echo 'Content that a non-logged in guest would see on this page...<br />'; } echo '<p>General content that all visitors would see</p>'; // independent non-logged in code some where else on the page - if(!$user->logged_in()){ echo 'Some more content that a non-logged in guest would see...<br />'; } ?> login_class.php <?php // login in form/form processing code to authenticate the visitor. // The net result it to set the status in the database to logged in and to set a session // variable to the username that identifies the logged in visitor. // detect direct access to included/required file if(strtolower(basename($_SERVER["SCRIPT_NAME"])) == strtolower(basename(__FILE__))){ exit('No Direct Access'); } class login_class { private $user_table; // used in queries private $salt_string; // used in queries (password) private $mysqli; // mysqli db object public function __construct() { require 'login_config.php'; // get the login specific config file // Create instance of db object, connect to database server and select database $this->mysqli = new mysqli($dbhost,$dbuser,$dbpwd,$dbname); // check connection if ($this->mysqli->connect_error){ $sys_error = sprintf("Database connection failed: %s\n", $this->mysqli->connect_error); // setup the system error message exit($sys_error); } // set class variables from config file variables $this->user_table = $user_table; $this->salt_string = $salt_string; } public function logged_in(){ return empty($_SESSION['current_user']) ? FALSE : TRUE; } // end of logged_in function public function user_name(){ return !empty($_SESSION['current_user']) ? $_SESSION['current_user'] : ''; } // end of user_name function public function logout_link(){ return '<a href="?action=logout">Log out</a><br />'; } // end of logout_link function public function login_box(){ // condition external inputs (actual/default values) $url_action = isset($_GET['action']) ? strtolower($_GET['action']) : ''; $form_submitted = isset($_POST['submit']) ? $_POST['submit'] : FALSE; $form_username = isset($_POST['username']) ? $_POST['username'] : ''; $form_password = isset($_POST['password']) ? $_POST['password'] : ''; // process any get action= switch ($url_action){ case 'logout': // if currently logged in, set status to logged out if($this->logged_in()){ $query = "UPDATE $this->user_table SET status = 0 WHERE username = '{$_SESSION['current_user']}' AND status = 1"; if(!$result = $this->mysqli->query($query)){ return FALSE; } $_SESSION['current_user'] = ''; } break; default: } // process the form data if the form has been submitted and you are not logged in if($form_submitted AND !$this->logged_in()) { $form_errors = array(); // array to hold any form validation errors // validate the form data if(empty($form_username)) { $form_errors[] = 'Please fill in the user name'; } else { // in a real script, you would check here for min length, mix of alpha-numeric... // the same checks done when creating a password, to insure that a wrong/hacked password // that produces the same hash as the real password is not being entered } if(empty($form_password)) { $form_errors[] = 'Please fill in the password'; } else { // in a real script, you would check here for min length, mix of alpha-numeric... } // if there were no form validation errors, use the data if(empty($form_errors)) { // authenticate the username/password against the database $q_username = $this->mysqli->real_escape_string($form_username); $q_password = md5($form_password . $this->salt_string); $q_pwd_length = strlen($form_password); // get length of entered pwd for check - guard against different pwd with same hash $query = "SELECT status FROM $this->user_table WHERE username = '$q_username' AND password = '$q_password' AND pwd_length = $q_pwd_length"; if(!$result = $this->mysqli->query($query)){ return FALSE; } if($result->num_rows == 0){ // there is no matching row $form_errors[] = 'The username or password is not correct'; // in a real script with bad attempt lockout, it would be ok to tell which piece of information was incorrect // you would also put the bad attempt lockout code here } else { // there was a matching row (UNIQUE INDEX insures there is only one), check the status $row = $result->fetch_object(); // 0 = logged out, 1 = logged in, 2 = disabled switch ($row->status) { case 0: // currently logged out, set status to logged in (if permitted) and set the session variable to identify the current visitor $query = "UPDATE $this->user_table SET status = 1 WHERE username = '$q_username' AND status = 0"; if(!$result = $this->mysqli->query($query)){ return FALSE; } // check if update changed the row to logged in (if admin disabled account at same time logging in, it won't update) if($this->mysqli->affected_rows == 1){ $_SESSION['current_user'] = $q_username; } break; case 1: // already logged in, set session variable to match // this means that you closed your brower while logged in and needed to re-authenticate to get to this point $_SESSION['current_user'] = $q_username; break; case 2: // account disabled $form_errors[] = 'Your account is disabled, contact support for assistance'; break; default: } } } } // The above code is just the form processing code. // You are at this point in this code if you are just a guest, you just logged in or you were already logged in. // If you are logged in, the status in the database must be checked to determine if you have been logged out due // to administrative action, inactivity, or to detect a hijacked session. if($this->logged_in()){ $query = "SELECT status FROM $this->user_table WHERE username = '{$_SESSION['current_user']}'"; if(!$result = $this->mysqli->query($query)){ return FALSE; } $row = $result->fetch_object(); // 0 = logged out, 1 = logged in, 2 = disabled switch ($row->status) { case 0: // status is currently logged out but your session says logged in, either you were // automatically logged out in the database due to inactivity or you logged out and someone // is using a session that was hijacked while you were logged in // make the session data match the database (logged out) $_SESSION['current_user'] = ''; $form_errors[] = 'You must log in again'; break; case 1: // status says logged in and session says logged in // this is the normal state and means you refreshed or browsed to a page while logged in // you would get any other variables here that a logged in visitor uses on the page break; case 2: // account disabled // the session says you logged in but your account has been disabled in the database $_SESSION['current_user'] = ''; $form_errors[] = 'Your account is disabled, contact support for assistance'; break; default: // unsupported value (should not happen) // take appropriate action (write to log file) here - } } // display the form if not logged in If(!$this->logged_in()){ // check for and display any form validation errors if(!empty($form_errors)){ // echo "Please correct these errors -<br />"; foreach($form_errors as $error){ echo "$error<br />"; } } // display the form, with any previously submitted values echo " <form method='post' action=''> Enter Username: <input type='text' name='username' value='$form_username'> Enter Password: <input type='text' name='password' value='$form_password'><br /> <input type='submit' name='submit' value='Submit'> </form> "; } else { // display user info if logged in // echo "Welcome: {$_SESSION['current_user']}, you are logged in<br />"; echo "Welcome: {$this->user_name()}, you are logged in<br />"; // you can use class method in a string echo $this->logout_link(); } } // end of login_box function } // end of class ?> login_config.php <?php // detect direct access to included/required file if(strtolower(basename($_SERVER["SCRIPT_NAME"])) == strtolower(basename(__FILE__))){ exit('No Direct Access'); } // contains login config information require $_SERVER['DOCUMENT_ROOT'] . '/dbinfo.php'; // get database login info $user_table = 'users'; // database table name $salt_string = "some 726rn junk &^$( string"; ?> Link to comment https://forums.phpfreaks.com/topic/174393-having-a-login-script-that-doesnt-redirect-to-a-page/#findComment-919752 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.