PHP - Redirect Issue
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! Similar TutorialsFirst let me say I am learning PHP as I do this, so bear with me if any of my mistakes are just silly! I have a log in system in place. I can register and send the e-mail. I have a log in page that allows the user to log in. If the wrong name/password combo is entered it displays an incorrect log in message on the same page. However, when the correct information is entered, it does not redirect to the proper page (play.php). Now if I am not logged in and I manually go to play.php via the address bar, it will redirect me to the error page (as it should). However if I do log in, and manually go to play.php, it will allow me access and does show the cookies (username and score) that I have set to print. Here are the codes I have for each page. Can someone please tell me where I am going wrong! (*on db.php I have tried with and without ob_start(); figuring at first I wouldn't need it because I did not output anything! I have tried tons of combinations including a log in function). on db.php <?php session_start(); mysql_connect("localhost", "dbuser", "dbpassword"); mysql_select_db("myDB"); { if (isset($_POST['username']) && isset($_POST['pword'])) { $username = mysql_real_escape_string($_POST['username']); $password = md5( mysql_real_escape_string($_POST['pword']) ); $sql = mysql_query("SELECT * FROM usersystem WHERE username = '$username' AND password = '$password' LIMIT 1"); $rows = mysql_num_rows($sql); if ($rows<1) { echo "&serverResponse=Incorrect username/password"; } else { ob_start; header( "Location: play.php" ) ; $_SESSION['username'] = $username; $result = mysql_query("SELECT total FROM usersystem WHERE username = '$username'") or die( mysql_error() ); $row=mysql_fetch_assoc($result); $total = $row['total']; setcookie("username", "$username", time()+3600); setcookie("total", "$total", time()+3600); } }} ?> on login.php <?php include("db.php"); ?> on play.php <?php include("db.php"); if ((isset($_COOKIE["username"])) && (isset ($_COOKIE["total"]))) { print ("&username=" . $_COOKIE["username"]); print ("&total=" . $_COOKIE["total"]);} else { ob_start(); header('Location: nogo.php'); } My profile pages can be accessed via domain.com/u/username When I am on them and I click a link that goes to /account-setting I get redirected to /u/account-settings which is not the correct path. I don't think this is a rewrite issue. Rewrite rule: RewriteRule ^u/(.*)$ /profile.php?u=$1 [QSA,L] On my profile page I have: Code: [Select] if (isset($_GET["u"])) { $username = mres($_GET["u"]); } else if (isset($user_info["username"])) { $username = mres($user_info["username"]); } The really odd thing is that when I hover over the link. Firefox even displays domain.com/account-settings in the explore at the bottom of the page. Any idea why this is getting rewritten? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <style> .error {color: #FF0000;} h6 { font-family: bookman old style; font-size:20px; text-align: center; font-weight: normal; } h5 { font-family: bookman old style; font-size:15px; text-align: center; font-weight: normal; } </style> <?php $nameErr = $emailErr = $websiteErr = $categoryErr; $name = $email = $comment = $website = $reset = $category; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) { $websiteErr = "URL is required"; } else { $website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["category"])) { $categoryErr = "Category is required"; } else { $category = test_input($_POST["category"]); } if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['website']) && !empty($_POST['category'])) { $myemail = "links@loadsofads.com"; $subject = "Link Submission"; $message = "Your Link Submission form has been submitted by: Website Name: $name E-mail: $email URL: $website Category: $category Description: $comment"; mail($myemail, $subject, $message); header('location:submitthanks.php'); }} function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <?php include'header.php'?> <h6>Link Submission</h6> <h5><p><span class="error">* required field.</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name Of Site: <input type="text" name="name" value=""> <span class="error">* <?php echo $nameErr;?></span> <br><br> E-mail: <input type="text" name="email" value=""> <span class="error">* <?php echo $emailErr;?></span> <br><br> URL: <input type="text" name="website" value=""> <span class="error">* <?php echo $websiteErr;?></span> <br><br> Description: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Category Of Site: <select size="1" name="category"> <option value=""> -- Please select -- </option> <option>Arts</option> <option>Business</option> <option>Computers</option> <option>Games</option> <option>Health</option> <option>Home</option> <option>Kids and Teens</option> <option>News</option> <option>Recreation</option> <option>Reference</option> <option>Science</option> <option>Shopping</option> <option>Society</option> <option>Sports</option> <option>World</option> </select><span class="error">* <?php echo $categoryErr;?></span> <br><br> <input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Reset Form"> </form> <?php include'footer.php'?>Hello All, OK so I have been at this for a few days now and everywhere I go to learn or read information it says the same thing, to redirect the code is header('location:mypage.php');exit(); but it just will not redirect it every thing I try it does not load the redirect page. it clears the form and sits there, I do not know why! Can please someone please help me and see why it is not doing it? Thanks Hi Everyone was kind enough to help with my last issue and am now nearly there. The data actually populates correctly now in my database, however, it will not direct me to my redirect. I get the error Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\loginsystem\Permnew.php:4) in C:\xampp\htdocs\loginsystem\Permnew.php on line 124 This is the redirect i am trying to do anyone any ideas? Thanks Steve
<?php require "header.php"; ?> <main> <div class="wrapper-main"> <div class="welcomelogged"> <p>Adding A Permanent New Starter<p> </div> <form class="form-addperm" action="" method="post"> <table id="Tableperm" width="1000px;" border="0"> <tr> <th align="right" scope="row"><label for="select">Week Commencing</label></th> <td><select name="WeekComm"> <option value="WC 6th April">WC 6th April</option> <option value="WC 13th April">WC 13th April</option> <option value="WC 20h April">WC 20h April</option> <option value="WC 27h April">WC 27h April</option> </select></td> </tr> <tr> <th align="right" scope="row"><label for="StartDate">Start Date</label></th> <td><input type="date" name="StartDate" placeholder="Start Date"></td> </tr> <tr> <th align="right" scope="row"><label for="select1">Consultant</label></th> <td><select name="Consultant"> <option value="Steven Buntin">Steven Buntin</option> <option value="Sam Ahmed">Sam Ahmed</option> <option value="David Millington">David Millington</option> <option value="Steven Nixon">Steven Nixon</option> <option value="Grahame Walsh">Grahame Walsh</option> <option value="Helal Ahmed">Helal Ahmed</option> </select></td> </tr> <tr> <th align="right" scope="row"><label for="FirstName">First Name</label></th> <td><input type="text" name="FirstName" placeholder="First Name"></td> </tr> <tr> <th align="right" scope="row"><label for="LastName">Last Name</label></th> <td><input type="text" name="LastName" placeholder="Last Name"></td> </tr> <tr> <th align="right" scope="row"><label for="ClientName">Client Name</label></th> <td><input type="text" name="ClientName" placeholder="Client Name"></td> </tr> <th align="right" scope="row"><label for="Position">Position</label></th> <td><input type="text" name="Position" placeholder="Position"></td> </tr> <th align="right" scope="row"><label for="Comments">Comments</label></th> <td><input type="text" name="Comments" placeholder="Comments"></td> </tr> <tr> <th align="right" scope="row"><label for="Salary">Salary</label></th> <td><input type="varchar" name="Salary" placeholder="Salary"></td> </tr> <tr> <th align="right" scope="row"><label for="ChargePercentage">Charge Percentage</label></th> <td><input type="varchar" name="ChargePercentage" placeholder="ChargePercentage"></td> </tr> <ty> <th align="right" scope="row"><label for="GPNotes">GP Notes</label></th> <td><input type="text" name="GPNotes" placeholder="GPNotes"></td> </tr> </table> <button type="submit" name="addstarter">Add Starter</button> </form> </div> </main> <?php $dBServername = "localhost"; $dBUsername = "root"; $dBPassword = ""; $dBName = "loginsystemtut"; mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); $conn = mysqli_connect($dBServername, $dBUsername, $dBPassword, $dBName); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } if (isset($_POST['addstarter'])) { $WeekComm = $_POST['WeekComm']; $StartDate = $_POST['StartDate']; $Consultant = $_POST['Consultant']; $FirstName = $_POST['FirstName']; $LastName = $_POST['LastName']; $ClientName = $_POST['ClientName']; $Position = $_POST['Position']; $Comments = $_POST['Comments']; $Salary = $_POST['Salary']; $ChargePercentage = $_POST['ChargePercentage']; $GPNotes = $_POST['GPNotes']; $sql = ("INSERT INTO permanent (WeekComm, StartDate, Consultant, FirstName, LastName, ClientName, Position, Comments, Salary, ChargePercentage, GpNotes) values (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { // If there is an error we send the user back to the signup page. header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt,"sssssssssss",$WeekComm,$StartDate,$Consultant,$FirstName,$LastName,$ClientName,$Position,$Comments,$Salary,$ChargePercentage,$GPNotes); mysqli_stmt_execute($stmt); } header("Location: ../loginsystem/permnew1.php?success"); exit(); } ?>
Is there a way to get current logged in username and based on that redirect to a different page? I’m using the following secure PHP login without MySql as a login system: https://sourceforge.net/projects/phploginbyvallastech/ Now I’m looking to redirect each logged in user to their personalized page. But I can’t figure out how to A) fetch the current logged in user and B) redirect multiple users. This code redirects to the latter address, but the username based redirect is not working: <?php session_start(); if ($_SESSION["username"]==User1){ header("location: user1content.php"); exit; } else { header("location: generalcontent.php"); exit; } { ?> <?php } ?>
So it’s clearly not fetching the logged in user. Though <?php echo $login->username; ?> fetches the username just fine. I'm trying to put together a script that redirects visitors based on their IP, user agent and/or referral url. Basically I want the script to scan these three factors from the visitor, if any of them turn out to match my redirect-requirement it redirects the user. I know the code is horribly coded, I'm incredibly new to the php-scene and consider myself a complete noob. As you can see I want redirected visitors to go to google.com and un-redirected to msn.com(examples). Really thankful for all the help I can get! Right now nothing works, any suggestions? <?php function redirect($page) { Header( "HTTP/1.1 301 Moved Permanently" ); header('Location: ' . $page); exit; } $referrals=array('pitchingit.org','referral2'); $badAgents = array("useragent1", "useragent2"); $deny = array("78.105.191..*","100.101.103..*"); if (in_array($_SERVER['HTTP_REFERER'], $referrals, FALSE)) { header("Location: http://www.google.com"); } else { header("Location: http://www.msn.com"); } if(in_array($_SERVER['HTTP_USER_AGENT'],$badAgents)) { redirect("http://www.google.com/"); exit(); } $add=$_SERVER['REMOTE_ADDR']; foreach ($deny as $ip) { if (preg_match("^.$add.*^",$ip)) { redirect("http://www.google.com"); } } redirect("http://www.msn.com"); ?> How can one re-direct a visitor, without using a header re-direct? I'd like a page to show up, then after about 5 seconds I need the visitor sent to another page. How can I do this? Hi, I have this code below which groups all the SubHeading together and then queries the same table to find RiskConsequence which are grouped that match SubHeading then to query this table one more last time with all the Risk Mitigation that matches the grouped RiskConsequence. Problem I get is it does the SubHeading, the RiskConsequences it only does one of them not all of them before it moves onto the RiskMitigation. I know I have a php coding issue just cant see the wood from the tree's as the queries work. Code: [Select] <?php include ("include.php"); $query = "SELECT * FROM tblriskassessmentdatabank GROUP BY SubHeading"; $results = mysql_query($query) or die("Error: " . mysql_error()); while($row1 = mysql_fetch_array($results)){ echo'<a href="#" onClick="return(changeDisplay(';echo"'";echo($row1[SubHeading]);echo"'))";echo'">';echo($row1[SubHeading]);echo'</a><br /><br />'; echo'<div id="';echo($row1[SubHeading]); echo'" class="HideText">'; $risksub = $row1[SubHeading]; $query1 = "SELECT * FROM tblriskassessmentdatabank GROUP By RiskConsequence"; $results1 = mysql_query($query1) or die("Error: " . mysql_error()); while($row2 = mysql_fetch_array($results1)){ echo'<a href="#" onClick="return(changeDisplay(';echo"'";echo($row2[RiskConsequence]);echo"'))";echo'">';echo($row2[RiskConsequence]);echo'</a><br />'; echo'<div id="';echo($row2[RiskConsequence]); echo'" class="HideText">'; $risksub1 = $row2[RiskConsequence]; $query1 = "SELECT * FROM tblriskassessmentdatabank WHERE RiskConsequence = '$risksub1'"; $results1 = mysql_query($query1) or die("Error: " . mysql_error()); while($row3 = mysql_fetch_array($results1)){ echo'<input name="checkbox[]" type="checkbox" id="checkbox[]" value="';echo($row3[IssueNumber]);echo'" /> <label for="checkbox[]"></label>';echo($row3[RiskMitigation]);echo'<br /><br />'; } echo'</div>'; } echo'</div>'; } ?> Folks, I remember once having a php or html5 issue where the first option had to be blank in the drop down. Otherwise, it wasn't working. What wasn't working ? How wasn't working ? I can't remember. either php had difficulty reading user input or the drop down was not showing any options. And so, I had to add a blank value. So, something like this wasn't working ...
<label for="tos_agreement">Agree to TOS or not ?</label> <select name="tos_agreement" id="tos_agreement"> <option value="yes">Yes</option> <option value="no">No</option> </select>
And, I think I added a blank value, at somebody's advice, to get it to work. I think it was something like this, if I remember correctly:
<label for="tos_agreement">Agree to TOS or not ?</label> <select name="tos_agreement" id="tos_agreement"> <option value=" ">Select here</option> <option value="yes">Yes</option> <option value="no">No</option> </select>
Or, maybe it was something like this:
<label for="tos_agreement">Agree to TOS or not ?</label> <select name="tos_agreement" id="tos_agreement"> <option value=" "></option> <option value="yes">Yes</option> <option value="no">No</option> </select>
I can't remember. All I remember slightly that there was a blank value. I been going through my php files to find that particular file to jog my memory but I failed to find it. Can you folks explain to me if a blank value is required or not ? What is the benefit/disaster of adding it and how should the blank value be added ? Show me an example.
Was this a php or html 5 issue ? Can anybody fugure ?
Thank You maybe a silly question, but when somebody visits my site i.e. domain.com i want it to redirect them to www.domain.com example can be seen @ facebook.com Ok I know I can redirect using: header( 'Location: URL' ) ; Now, is there a way to delay this after a short while of displaying or would I have to use Javascript? Hi all, I have a page url that looks like this: jobs.php?view=view&id=5 Their is a login on this page, the form ends with this command: header("Location: ".$session->referrer); The fuction for this is: <?php 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']; } ?> Basically $this->url = $_SESSION['url'] = $_SERVER['PHP_SELF']; seems to cut my url to: jobs.php instead of: jobs.php?view=view&id=5 Can anyone here tell me how to fix this? Thanks Guys if you go to this page here http://www.nikita-andrews.com/ingrid/?page_id=34 you see it is a three column grid layout if you click on image and go to single post you will see above the post it will either say HOME/PORTFOLIO/CURRENT PAGE or HOME/(CATEGORY)/CURRENT PAGE if you click on Portfolio or Category (whichever category it may be) it takes you back to a vertical list of all the post in the category like such http://www.nikita-andrews.com/ingrid/?cat=5 ... is there a way to redirect that link to go back to the 3 grid layout portfolio or portfolio category page? Using wordpress ... not sure where the php would be located. Im guessing in single.php but not sure where the code for that function is located in there Hello everyone, I am new to php,and i am making my website......where i am unable to redirect a user to his respctive homepage.. Can anyone help me out with a sample script.......... Thanks, cool_techie what the syntax to get out from the actual folder and redirect to some file outside ?? <?php header("Location: ???file.php"); exit; ?> Can anyone enlighten me on why this doesn't redirect and if there's a better / different way of achieving a redirect deep within a page?
<?php echo"anything"; // remove this echo or even make it blank and it redirects as expected header("location:blah.php"); ?> Hi guys, this is my first post here. I'm looking for some help with some code for a form submission. It all works fine but if I add in a redirect using the advice found he http://www.computing.net/answers/webdevel/redirection-after-submit-php-form/3580.html. I'm using the following code: Code: [Select] <?php header ('Location: http://www.jwhunterhill.co.uk/return.html'); exit (); if(isset($_POST['email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "xxx@gmail.com"; $email_subject = "E-mail from JWHunterHill.co.uk"; function died($error) { // your error code can go here echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.<br /><br />"; echo $error."<br /><br />"; echo "Please go back and fix these errors.<br /><br />"; die(); } // validation expected data exists if(!isset($_POST['first_name']) || !isset($_POST['last_name']) || !isset($_POST['email']) || !isset($_POST['telephone']) || !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $first_name = $_POST['first_name']; // required $last_name = $_POST['last_name']; // required $email_from = $_POST['email']; // required $telephone = $_POST['telephone']; // not required $comments = $_POST['comments']; // required $error_message = ""; $email_exp = "^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$"; if(!eregi($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.<br />'; } $string_exp = "^[a-z .'-]+$"; if(!eregi($string_exp,$first_name)) { $error_message .= 'The First Name you entered does not appear to be valid.<br />'; } if(!eregi($string_exp,$last_name)) { $error_message .= 'The Last Name you entered does not appear to be valid.<br />'; } if(strlen($comments) < 2) { $error_message .= 'The Comments you entered do not appear to be valid.<br />'; } if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "First Name: ".clean_string($first_name)."\n"; $email_message .= "Last Name: ".clean_string($last_name)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Telephone: ".clean_string($telephone)."\n"; $email_message .= "Comments: ".clean_string($comments)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?> <!-- include your own success html here --> Thank you for contacting me. I will be in touch with you very soon. <?php } ?> As I said the code works fine just if I include the redirect, the form will not send me an e-mail as required. Could you help me out please? Thanks in advance, Jonathon <?php $get = fetch("SELECT number FROM dom") if "$get = 1" echo "<meta http-equiv='refresh' content='0;url=http://toxicpets.co.uk/down_for_maitenence.php'>"; elseif "$get = 0" echo "<meta http-equiv='refresh' content='0;url=http://toxicpets.co.uk/index.php'>"; ?> is this code right??? how do i redirect page within an if/else statement Can someone tell me how to fix this At the top of every page i have this. Code: [Select] <?php include('GiveAway_Control.php');?> <!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" lang="en" xml:lang="en"> <head> in the GiveAway_Control.php there is the Code: [Select] header("Location: http://www.domain.com/winner.html"); /* Redirect browser */ The GiveAway_Control.php has NO echo statements what so ever. |