HeathP Posted November 28, 2011 Share Posted November 28, 2011 Hi. I'm having an issue with my login code. When a user logs in and selects "remember me", everything works fine. The user will be redirected back to myaccount.php. However, if the user logs in and does not select "remember me", the user will not be redirected if he or she goes to index.php. This leads me to believe that my statement is returning that there is no session and causing it to not redirect. my functions: <?php define ("DB_HOST", "localhost"); // set database host define ("DB_USER", "campusso_campus"); // set database user define ("DB_PASS",""); // set database password define ("DB_NAME","campusso_maindb"); // set database name $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection."); $db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database"); /* Registration Type (Automatic or Manual) 1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link) 0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually) */ $user_registration = 1; // set 0 or 1 define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days) define('SALT_LENGTH', 9); // salt for password define ("ADMIN_NAME", "admin"); /* Specify user levels */ define ("ADMIN_LEVEL", 5); define ("USER_LEVEL", 1); define ("GUEST_LEVEL", 0); function loggedin() { if (isset($_SESSION['last_name'])|| isset($_COOKIE['user_id'])) { $loggedin = TRUE; return $loggedin; } } function page_protect() { session_start(); global $db; /* Secure against Session Hijacking by checking user agent */ if (isset($_SESSION['HTTP_USER_AGENT'])) { if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])) { logout(); exit; } } // before we allow sessions, we need to check authentication key - ckey and ctime stored in database /* If session not , check for cookies set by Remember me */ if (!isset($_SESSION['user_id']) && !isset($_SESSION['first_name']) ) { if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){ /* we double check cookie expiry time against stored in database */ $cookie_user_id = filter($_COOKIE['user_id']); $rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error()); list($ckey,$ctime) = mysql_fetch_row($rs_ctime); // coookie expiry if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) { logout(); } /* Security check with untrusted cookies - dont trust value stored in cookie. /* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/ if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && isUserID($_COOKIE['first_name']) && $_COOKIE['user_key'] == sha1($ckey) ) { session_regenerate_id(); //against session fixation attacks. $_SESSION['user_id'] = $_COOKIE['user_id']; $_SESSION['first_name'] = $_COOKIE['first_name']; /* query user level from database instead of storing in cookies */ list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'")); $_SESSION['user_level'] = $user_level; $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']); } else { logout(); } } else { header("Location: login.php"); exit(); } } } function filter($data) { $data = trim(htmlentities(strip_tags($data))); if (get_magic_quotes_gpc()) $data = stripslashes($data); $data = mysql_real_escape_string($data); return $data; } function EncodeURL($url) { $new = strtolower(ereg_replace(' ','_',$url)); return($new); } function DecodeURL($url) { $new = ucwords(ereg_replace('_',' ',$url)); return($new); } function ChopStr($str, $len) { if (strlen($str) < $len) return $str; $str = substr($str,0,$len); if ($spc_pos = strrpos($str," ")) $str = substr($str,0,$spc_pos); return $str . "..."; } function isEmail($email){ return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE; } function isUserID($username) { if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) { return true; } else { return false; } } function isURL($url) { if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) { return true; } else { return false; } } function checkPwd($x,$y) { if(empty($x) || empty($y) ) { return false; } if (strlen($x) < 4 || strlen($y) < 4) { return false; } if (strcmp($x,$y) != 0) { return false; } return true; } function GenPwd($length = 7) { $password = ""; $possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels $i = 0; while ($i < $length) { $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); if (!strstr($password, $char)) { $password .= $char; $i++; } } return $password; } function GenKey($length = 7) { $password = ""; $possible = "0123456789abcdefghijkmnopqrstuvwxyz"; $i = 0; while ($i < $length) { $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); if (!strstr($password, $char)) { $password .= $char; $i++; } } return $password; } function logout() { global $db; session_start(); if(isset($_SESSION['user_id']) || isset($_COOKIE['user_id'])) { mysql_query("update `users` set `ckey`= '', `ctime`= '' where `id`='$_SESSION[user_id]' OR `id` = '$_COOKIE[user_id]'") or die(mysql_error()); } /************ Delete the sessions****************/ unset($_SESSION['user_id']); unset($_SESSION['first_name']); unset($_SESSION['last_name']); unset($_SESSION['user_level']); unset($_SESSION['HTTP_USER_AGENT']); session_unset(); session_destroy(); /* Delete the cookies*******************/ setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/"); setcookie("first_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/"); setcookie("last_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/"); setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/"); header("Location: index.php"); } // Password and salt generation function PwdHash($pwd, $salt = null) { if ($salt === null) { $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH); } else { $salt = substr($salt, 0, SALT_LENGTH); } return $salt . sha1($pwd . $salt); } function checkAdmin() { if($_SESSION['user_level'] == ADMIN_LEVEL) { return 1; } else { return 0 ; } } ?> login.php: <?php include 'dbc.php'; $user_email = $_POST['usr_email']; $pass = $_POST['pwd']; $err = array(); foreach($_GET as $key => $value) { $get[$key] = filter($value); //get variables are filtered. } if ($user_email) { foreach($_POST as $key => $value) { $data[$key] = filter($value); // post variables are filtered } $user_email = $data['usr_email']; $pass = $data['pwd']; if (strpos($user_email,'@') === false) { $user_cond = "user_name='$user_email'"; } else $user_cond = "user_email='$user_email'"; $result = mysql_query("SELECT `id`,`pwd`,`first_name`,`last_name`,`approved`,`user_level` FROM users WHERE $user_cond AND `banned` = '0' ") or die (mysql_error()); $num = mysql_num_rows($result); // Match row found with more than 1 results - the user is authenticated. if ( $num > 0 ) { list($id,$pwd,$first_name,$last_name,$approved,$user_level) = mysql_fetch_row($result); if(!$approved) { $err[] = "Account not activated. Please check your email for activation code"; } //check against salt if ($pwd === PwdHash($pass,substr($pwd,0,9))) { if(empty($err)){ // this sets session and logs user in session_start(); session_regenerate_id (true); //prevent against session fixation attacks. // this sets variables in the session //update the timestamp and key for cookie $stamp = time(); $ckey = GenKey(); mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error()); //set a cookie if(isset($_POST['remember'])){ setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("first_name",$_SESSION['first_name'], time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("last_name",$_SESSION['first_name'], time()+60*60*24*COOKIE_TIME_OUT, "/"); header("Location: myaccount.php"); die(); } else if(!isset($_POST['remember'])){ $_SESSION['user_id']= $id; $_SESSION['first_name'] = $first_name; $_SESSION['last_name'] = $last_name; $_SESSION['user_level'] = $user_level; $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']); header("Location: myaccount.php"); die(); } else $err[] = "Invalid Login. Please try again with correct user email and password."; } else $err[] = "Invalid Login. Please try again with correct user email and password."; } else $err[] = "Invalid Login. Please try again with correct user email and password."; } else $err[] = "Error - Invalid login. No such user exists"; } else $err[] = "Error - Invalid login. No such user exists"; ?> <html> <head> <title>Members Login</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="style.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" media="print" href="style.css" /> <link rel="stylesheet" type="text/css" media="screen" href="style.css" /> <script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#logForm").validate(); }); </script> </head> <body> <!--Header Background Part Starts --> <div id="header-bg"> <!--Header Contant Part Starts --> <div id="header"> <a href="index.php"><img src="images/logo.gif" alt="CS" border="0" class="logo" title="Campus Social" /></a> <!--Login Background Starts --> <div id="login-bg"> <!--Login Area Starts --> <!--Login Area Ends --> </div> <!--Login Background Ends --> <br class="spacer" /> </div> <!--Header Contant Part Ends --> </div> <!--Header Background Part Ends --> <!--Main Area Background Starts --> <div id="CS-bg"> <!--Main Area Starts Starts --> <div id="CS-part2"><br> <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main"> <tr> <td colspan="3"> </td> </tr> <tr> <td width="160" valign="top"><p> </p> <p> </p> <p> </p> <p> </p> <p> </p></td> <td width="732" valign="top"><p> </p> <h3 id="black">Login Users </h3> <p> <?php /******************** ERROR MESSAGES************************************************* This code is to show error messages **************************************************************************/ if(!empty($err)) { echo "<div class=\"msg\">"; foreach ($err as $e) { echo "$e <br>"; } echo "</div>"; } /******************************* END ********************************/ ?></p> <form action="login.php" method="post" name="logForm" id="logForm" > <table width="65%" border="0" cellpadding="4" cellspacing="4" class="loginform"> <tr> <td colspan="2"> </td> </tr> <tr> <td width="28%">Username / Email</td> <td width="72%"><input name="usr_email" type="text" class="required" id="black" size="25"></td> </tr> <tr> <td>Password</td> <td><input name="pwd" type="password" class="required password" id="black" size="25"></td> </tr> <tr> <td colspan="2"><div align="center"> <input name="remember" type="checkbox" id="remember"> Remember me</div></td> </tr> <tr> <td colspan="2"> <div align="center"> <p> <input name="doLogin" type="submit" id="doLogin3" value="Login"> </p> <p><a href="index.php">Register Free</a><font color="#000"> |</font> <a href="forgot.php">Forgot Password</a> </p> </tr> </table> <div align="center"></div> <p align="center"> </p> </form> <p> </p> </td> <td width="196" valign="top"> </td> </tr> <tr> <td colspan="3"> </td> </tr> </table> </div> <!--Footer Part Starts --> <div id="footer-bg"> <!--Footer Menu Part Starts --> <div id="footer-menu"> <ul class="footMenu"> <li class="noDivider"><a href="#" title="Home">Home</a></li> <li><a href="#" title="About">About</a></li> <li><a href="#" title="Services">Services</a></li> <li><a href="#" title="Support">Support</a></li> <li><a href="#" title="Chat">Chat</a></li> <li><a href="#" title="History">History</a></li> <li><a href="#" title="Contact">Contact</a></li> </ul> <br class="spacer" /> <p class="copyright">Copyright © Campus Social 2011 All Rights Reserved</p> </div> <!--Footer Menu Part Ends --> </div> <!--Footer Part Ends --> </body> </html> index.php: <?php $user = $_SESSION['user_id']; include 'dbc.php'; if (loggedin()) { header("Location: myaccount.php"); exit(); } $err = array(); if($_POST['doRegister'] == 'Register') { /******************* Filtering/Sanitizing Input ***************************** This code filters harmful script code and escapes data of all POST data from the user submitted form. *****************************************************************/ foreach($_POST as $key => $value) { $data[$key] = filter($value); } if(empty($data['first_name']) || strlen($data['first_name']) < 1) { $err[] = "ERROR - Invalid name. Please enter atleast 3 or more characters for your name"; //header("Location: register.php?msg=$err"); //exit(); } if(empty($data['last_name']) || strlen($data['last_name']) < 1) { $err[] = "ERROR - Invalid Last name. Please enter atleast 3 or more characters for your name"; //header("Location: register.php?msg=$err"); //exit(); } // Validate User Name if (!isUserID($data['user_name'])) { $err[] = "ERROR - Invalid user name. It can contain alphabet, number and underscore."; //header("Location: register.php?msg=$err"); //exit(); } // Validate Email if(!isEmail($data['usr_email'])) { $err[] = "ERROR - Invalid email address."; //header("Location: register.php?msg=$err"); //exit(); } // Check User Passwords if (!checkPwd($data['pwd'],$data['pwd2'])) { $err[] = "ERROR - Invalid Password or mismatch. Enter 5 chars or more"; //header("Location: register.php?msg=$err"); //exit(); } $user_ip = $_SERVER['REMOTE_ADDR']; // stores sha1 of password $sha1pass = PwdHash($data['pwd']); // Automatically collects the hostname or domain like example.com) $host = $_SERVER['HTTP_HOST']; $host_upper = strtoupper($host); $path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Generates activation code simple 4 digit number $activ_code = rand(1000,9999); $usr_email = $data['usr_email']; $user_name = $data['user_name']; $rs_duplicate = mysql_query("select count(*) as total from users where user_email='$usr_email' OR user_name='$user_name'") or die(mysql_error()); list($total) = mysql_fetch_row($rs_duplicate); if ($total > 0) { $err[] = "ERROR - The username/email already exists. Please try again with different username and email."; //header("Location: register.php?msg=$err"); //exit(); } /***************************************************************************/ if(empty($err)) { $datex = date('W y'); $datey = date('m y'); $sql_insert = "INSERT into `users` (`first_name`,`last_name`,`user_email`,`pwd`,`address`,`tel`,`fax`,`website`,`date`,`users_ip`,`activation_code`,`country`,`user_name`,`users_week`,`users_month` ) VALUES ('$data[first_name]','$data[last_name]','$usr_email','$sha1pass','$data[address]','$data[tel]','$data[fax]','$data[web]' ,now(),'$user_ip','$activ_code','$data[country]','$user_name','$datex','$datey' ) "; mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error()); $user_id = mysql_insert_id($link); $md5_id = md5($user_id); mysql_query("update users set md5_id='$md5_id' where id='$user_id'"); // echo "<h3>Thank You</h3> We received your submission."; if($user_registration) { $a_link = " *****ACTIVATION LINK*****\n http://$host$path/activate.php?user=$md5_id&activ_code=$activ_code "; } else { $a_link = "Your account is *PENDING APPROVAL* and will be soon activated the administrator. "; } $message = "Hello \n Thank you for registering with us. Here are your login details...\n User ID: $user_name Email: $usr_email \n Passwd: $data[pwd] \n $a_link Thank You Administrator $host_upper ______________________________________________________ THIS IS AN AUTOMATED RESPONSE. ***DO NOT RESPOND TO THIS EMAIL**** "; mail($usr_email, "Login Details", $message, "From: \"Member Registration\" <auto-reply@$host>\r\n" . "X-Mailer: PHP/" . phpversion()); header("Location: thankyou.php"); exit(); } } ?> <!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=iso-8859-1" /> <title>Campus Social</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" media="print" href="style.css" /> <link rel="stylesheet" type="text/css" media="screen" href="style.css" /> <script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> <script> $(document).ready(function(){ $.validator.addMethod("username", function(value, element) { return this.optional(element) || /^[a-z0-9\_]+$/i.test(value); }, "Username must contain only letters, numbers, or underscore."); $("#regForm").validate(); }); </script> </head> <body> <!--Header Background Part Starts --> <div id="header-bg"> <!--Header Contant Part Starts --> <div id="header"> <a href="index.php"><img src="images/logo.gif" alt="CS" border="0" class="logo" title="Campus Social" /></a> <!--Login Background Starts --> <div id="login-bg"> <!--Login Area Starts --> <div id="login-area"> <form action="login.php" method="POST" name="logForm" id="logForm" > <input style='display:list-item;' id="input1" name="usr_email" type="text" id="txtbox" value="Username/E-Mail" onclick="this.value = ( this.value == this.defaultValue ) ? '' : this.value;return true;"/> <input style='display:list-item;' id="input1" name="pwd" type="password" id="txtbox" value="Password" onclick="this.value = ( this.value == this.defaultValue ) ? '' : this.value;return true;"/> <input type="image" src="images/login-btn.gif" class="login-btn" alt="Login" name="doLogin" id="login"/> <input type="checkbox" value='yes' name="remember" id="remember"/> Remember Me <a class="move" href="forgot.php">Forgot Password </a> </form> </div> <!--Login Area Ends --> </div> <!--Login Background Ends --> <br class="spacer" /> </div> <!--Header Contant Part Ends --> </div> <!--Header Background Part Ends --> <!--Main Area Background Starts --> <div id="CS-bg"> <!--Main Area Starts Starts --> <div id="CS-part2"><br><br><br> <p id="statementtop">THE BEST RESOURCE FOR COLLEGE STUDENTS SINCE RAMEN NOODLES</p> </div> <div id="CS-part"> <!--Left Area Starts --> <div id="CS-left"> <img src="images/happy.jpg" alt="CS"/> </div> <!--Left Area Ends Ends --> <!--Right Area Starts --> <div id="CS-right"> <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main"> <tr> <td colspan="3"> </td> </tr> <tr> <td width="160" valign="top"><p> </p> <p> </p> <p> </p> <p> </p> <p> </p></td> <td width="732" valign="top"><p> <?php if (isset($_GET['done'])) { ?> <h2>Thank you</h2> Your registration is now complete and you can <a href="login.php">login here</a>"; <?php exit(); } ?></p> <h3 class="titlehdr">Free Registration / Signup</h3> <p>Please register a free account, before you can start posting your ads. Registration is quick and free! Please note that fields marked <span class="required">*</span> are required.</p> <?php if(!empty($err)) { echo "<div class=\"msg\">"; foreach ($err as $e) { echo "* $e <br>"; } echo "</div>"; } ?> <br> <form action="index.php" method="post" name="regForm" id="regForm" > <table width="95%" border="0" cellpadding="3" cellspacing="3" class="forms"> <tr> <td colspan="2">First Name<span class="required"><font color="#CC0000">*</font></span><br> <input name="first_name" type="text" id="full_name" size="40" class="required"></td> </tr> <tr> <td colspan="2">Last Name<span class="required"><font color="#CC0000">*</font></span><br> <input name="last_name" type="text" id="full_name" size="40" class="required"></td> </tr> <tr> <input type="hidden" value="not set" name="address" cols="40" rows="4" id="address" class="required"></textarea> </tr> <tr> <input type="hidden" value="not set" name="country" class="required" id="select8"> </tr> <input type="hidden" value="not set" name="tel" type="text" id="tel" class="required"> <input type="hidden" value="not set" name="fax" type="text" id="fax"> <input name="web" type="hidden" value="not set"> <tr> <td colspan="2"><h4><strong>Login Details</strong></h4></td> </tr> <tr> <td>Username<span class="required"><font color="#CC0000">*</font></span><br/> <input name="user_name" type="text" id="user_name" class="required username" onblur='$("#checkid").html("Please wait..."); $.get("checkuser.php",{ cmd: "check", user: $("#user_name").val() } ,function(data){ $("#checkid").html(data); });' minlength="5" > <span style="color:red; font: bold 12px verdana; " id="checkid" ></span> </td> </tr> <tr> <td>Your Email<span class="required"><font color="#CC0000">*</font></span> <br/> <input name="usr_email" type="text" id="usr_emailx" onblur='$("#checkid2").html("Please wait..."); $.get("check2.php",{ cmd: "check", email: $("#usr_emailx").val() } ,function(data){ $("#checkid2").html(data); });' class="required email"> <span style="color:red; font: bold 12px verdana; " id="checkid2" ></span> </tr> <tr> <td>Password<span class="required"><font color="#CC0000">*</font></span> <br/> <input name="pwd" type="password" class="required password" minlength="5" id="pwd"> <span class="example">** 5 chars minimum..</span></td> </tr> <tr> <td>Retype Password<span class="required"><font color="#CC0000">*</font></span> <br/> <input name="pwd2" id="pwd2" class="required password" type="password" minlength="5" equalto="#pwd"></td> </tr> </table> <p align="center"> <input name="doRegister" type="submit" id="doRegister" value="Register"> </p> </form> </td> <td width="196" valign="top"> </td> </tr> <tr> <td colspan="3"> </td> </tr> </table> </div> <!--Right Area Ends --><br class="spacer" /> </div> <!--Main Area Ends --> </div> <!--Our Company Bacground Part Ends --> <!--Footer Part Starts --> <div id="footer-bg"> <!--Footer Menu Part Starts --> <div id="footer-menu"> <ul class="footMenu"> <li class="noDivider"><a href="#" title="Home">Home</a></li> <li><a href="#" title="About">About</a></li> <li><a href="#" title="Services">Services</a></li> <li><a href="#" title="Support">Support</a></li> <li><a href="#" title="Chat">Chat</a></li> <li><a href="#" title="History">History</a></li> <li><a href="#" title="Contact">Contact</a></li> </ul> <br class="spacer" /> <p class="copyright">Copyright © Campus Social 2011 All Rights Reserved</p> </div> <!--Footer Menu Part Ends --> </div> <!--Footer Part Ends --> </body> </html> Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/251934-redirect-issue/ Share on other sites More sharing options...
HeathP Posted November 28, 2011 Author Share Posted November 28, 2011 anybody? Quote Link to comment https://forums.phpfreaks.com/topic/251934-redirect-issue/#findComment-1291962 Share on other sites More sharing options...
ManiacDan Posted November 28, 2011 Share Posted November 28, 2011 If some behavior leads you to believe there is a specific error condition, check it. Why do I have to say "what are the contents of the session when this happens?" Check that yourself. If something is wrong, dump the relevant variables to the screen or a log file until you figure out what the problem is. Quote Link to comment https://forums.phpfreaks.com/topic/251934-redirect-issue/#findComment-1291973 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.