PHP - A Little Problem With Sessions And Browser History
hello guys, this is my first post on this forum and I really need your help on this.
What I have is: I created a login page a home page and a index page. The index page checks if the session is set. If it's not the login page will be shown. If it is the homepage will be shown. Whenever the user logs in, the session gets set. The problem is is that whenever I login and the user presses the back button on his browser my session will always be returned false which means that whenever a user has logged in, the index page doesn't show home but shows the login page again even though the user has already logged in. Here is my code to make you understand a little bit better: session.php: Code: [Select] <?php class Session { function __construct() { } function set($name, $value) { $_SESSION[$name] = $value; } function get($name) { return $_SESSION[$name]; } function stopSession() { unset($_SESSION); session_destroy(); } function startSession() { if(!isset($_SESSION)) { session_start(); } } function check_session() { if(isset($_SESSION['username']) && !empty($_SESSION['username'])) { return true; } else { return false; } } } ?> login.php: Code: [Select] <?php class Handler_Login extends Action_Handler { function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { $password = $_POST['password']; $username = $_POST['username']; $login = $this->dbh->Login($username, $password); if ($login == true) { $this->session->startSession(); $this->session->set('username', $username); $this->view->displayHome(); $this->view->display(); } else { //This is going to get more advanced later on, I'm currently working on resolving my session issue before I continue on this. echo "you are not logged in"; } } } ?> index.php: Code: [Select] <?php class Handler_home extends Action_Handler { public function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { // for some reason this always returns false when the user goes back in history :( if ($this->session->check_session() == false) { $this->view->displayLogin(); $this->view->display(); } else { $this->view->displayHome(); $this->view->display(); } } } ?> anyone has an idea why the login page is always shown ? Similar TutorialsDear fourm, i am wondering if anyone can shed some light on this form submission problem with back/forward buttons. long story short: i used to make a form, then submit to a form process php file. errors were difficult to deal with. Thus, many people tell me to submit to the same page. I now submit to the same page. my homepage has a login button. i use a csrf token in a hidden input matched with a session variable. i decided to submit to same page and handle the submit like so: if server request-method = post and isset input name and isset session token then check the token with hash_equals if everything matches then show the login page. i don't have a problem with the form and the form submission processing. everything i fine. now when i use the browser refresh button on the login page, i am sent back to the homepage. all is good. when i press the back button, i go back to the homepage again. super. then i press the forward button in the browser and i get a not connected error. the back button now also shows this error. i tinkered around a bit and added crazy ideas and it worked one time with unset($_POST) as an else to the if mentioned above. the idea is that if server request-method is post without an else. the page is listed below for any get request to process. i assume that the browser is trying to repost data is empty but my if statement should kick it out to the get code, right? what i want is to unset the csrf token and the matching session token for security purposes. i suppose that this breaks the back/forward buttons? how can i get the browser to show the homepage regardless of the post situation? there must be a logical answer. something in my code is breaking this an preventing the browser from simply loading the home page any help is greatly appreciated! Thank you. Hello everyone, I am having a problem since some time now and need some help. I have created a login page where the user has to input a username and password to login. The username will be put in a session and when the user logs out the session data and session itself gets destroyed. However when I go back in the browser history to the page where I logged in I get the "famous" resend information dialog that asks you to resend the information from the login form. Which means that all the post data gets resend and the user logs in again without having to put in a username and password. Here is my code: Login.tpl: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Snitch</title> <link rel="stylesheet" type="text/css" href="templates/css/snitch1440x900.css" /> </head> <body> <div id="login-achtergrond"> <div id="login"> <form action="." id="loginform" name="login" method="post"> <input type="hidden" name="actie" value="Login"></input> <input type="text" id="username" name="username" value="" style="opacity:0.7;filter:alpha(opacity=70)"></input> <input type="password" id="password" name="password" value="" style="opacity:0.7;filter:alpha(opacity=70)"></input> <input id="aanmelden" type="submit" name="submit" value="" style="opacity:0;filter:alpha(opacity=0)"> </form> </div> <div id="registreer"> </div> </div> </body> </html> Here is the code of my login page (I created this in a OOP way): Code: [Select] <?php class Handler_Login extends Actie_Handler { function __construct($actie_handle) { parent::construct($actie_handle); $this->actie = $actie_handle; } function secured_handler() { if ($this->session->check_session() == false) { $password = $_POST['password']; $username = $_POST['username']; $login = $this->dbh->Login($username, $password); if ($login == true) { $this->session->set('username', $username); $this->view->displayHome(); $this->view->display(); } else { echo "You are not logged in!"; } unset($_POST['password']); unset($_POST['username']); } if ($this->session->check_session() == true) { $this->view->displayHome(); $this->view->display(); } } } ?> Here is the code of my logout: Code: [Select] <?php class Handler_Loguit extends Actie_Handler { function __construct($actie_handle) { parent::construct($actie_handle); $this->actie = $actie_handle; } function secured_handler() { $this->session->stopSession(); $this->view->displayLogin(); $this->view->display(); } } ?> Here is the code of my session: Code: [Select] <?php class Session { function __construct() { if(!isset($_SESSION)) { session_start(); } } function set($name, $value) { $_SESSION[$name] = $value; } function get($name) { return $_SESSION[$name]; } function stopSession() { $_SESSION = array(); //even though I don't use any cookies someone told me that I had to remove the cookie of the session to completely destroy it? //please tell me if this is correct if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000, '/'); } session_destroy(); } function session_message($naam) { return print_r($_SESSION[$naam]); } function check_session() { if(isset($_SESSION['username']) && !empty($_SESSION['username'])) { return true; } else { return false; } } } ?> this is the code of my view for those who might be interested: Code: [Select] <?php class view_manager { private $tpl; function __construct() { } function displayStatus() { $status = file_get_contents("templates/status.tpl"); $this->tpl = str_replace("%content%", $status, $this->tpl); } function displayLogin() { $this->tpl = file_get_contents("templates/login.tpl"); } function displayHome() { $this->tpl = file_get_contents("templates/home.tpl"); } function display() { echo $this->tpl; } } ?> using a header to redirect to the login page is not going to work since I use my view_manager to display the pages. Does anyone know of any solution to get rid of that stupid resend information dialog without using a header? I tryed unsetting the values of POST in my login code but that did not seem to work. Please help me out I've been looking for an answer for over 1 and a half week so far Is there anyone who knows how to remove the POST data from a form when the user goes back in browser history? If it's not possible, is there any solution except using a header? It appears that my '/tmp' folder on my shared hosting (GoDaddy) account is full with session files and it seems I have to wait (up to 72hrs) for their hopeless admins to clear out the folder. The strange things is everything was working fine a couple of days ago. Now sometimes I get errors on my PHP page saying disk is full and session cache error. Sometimes don't even get these errors. I can't seem to get back these errors now. Is there anyway to generate session or disk errors in PHP? Also, the login page doesn't work. It just doesn't login and reloads itself each time. I think it might be due to either the '/tmp' folder being full or it's getting confused with session variables that haven't been destroyed. I'm really not sure? Any help or insight would be much appreciated. Class creating the session variables and verifying login: Code: [Select] <?php session_start(); //global $loginTime; /** * LoginSystem * * Simple Login system with sessions and MySQL User DB * * @version 1.0 * @author A.Surrey (www.surneo.com) * * */ class LoginSystem { var $db_host, $db_name, $db_user, $db_password, $connection, //$userid, //added by IH 18-January-2011 $username, $password, $userip, $loginTime, $timeout; /** * Constructor */ function LoginSystem() { require_once('../../config/settings.php'); $this->db_host = $dbhost; $this->db_name = $dbname; $this->db_user = $dbuser; $this->db_password = $dbpassword; } /** * Check if the user is logged in * * @return true or false */ function isLoggedIn() { if($_SESSION['LoggedIn']) { return true; } else return false; } /** * Check username and password against DB * * @return true/false */ //function doLogin($username, $password) function doLogin($username, $password, $userip) { $timezone = 0; //(GMT -5:00) EST (U.S. & Canada) $loginTime = gmdate("Y-m-j H:i:s", time() + 3600*($timezone+date("I"))); $this->connect(); $this->username = $username; $this->password = $password; $this->userip = $userip; // check db for user and pass here. //$sql = sprintf("SELECT UserID, UserName, Password FROM Users WHERE UserName = '%s' and Password = '%s'", $sql = sprintf("SELECT UserID, UserName, FullName, Password FROM Users WHERE UserName = '%s' and Password = '%s' AND ActiveUser = '1'", $this->clean($this->username), md5($this->clean($this->password))); $result = mysql_query($sql, $this->connection); // If no user/password combo exists return false if(mysql_affected_rows($this->connection) != 1) { $this->disconnect(); return false; } else // matching login ok { $row = mysql_fetch_assoc($result); $userid = $row['UserID']; // more secure to regenerate a new id. session_regenerate_id(); //set session vars up $_SESSION['LoggedIn'] = true; $_SESSION['userName'] = $this->username; $_SESSION['userID'] = $row['UserID']; $_SESSION['fullName'] = $row['FullName']; //$this->getLoginTime(); //return $this->loginTime; //#### WORKING QUERY - MANUAL DATE VALUE #### //$sql2 = 'UPDATE Users SET LastLogin = "2011-01-18 23:55:32" WHERE UserID = "' . $userid.'"'; //#######################// //$sql2 = 'UPDATE Users SET LastLogin = "'.$loginTime.'" WHERE UserID = "'.$userid.'"'; $sql2 = 'UPDATE Users SET LastLogin = "'.$loginTime.'", UserIP = INET_ATON("'.$this->userip.'") WHERE UserID = "'.$userid.'"'; $result2 = mysql_query($sql2, $this->connection); //echo '<script>alert("'.$sql2.'");</script>'; } $this->disconnect(); return true; } function sessionTimer() { //unset($_SESSION['timeout']); session_start(); $this->inactivesession = $inactivesession; // set timeout period in seconds (14400 = 4 hours) $this->inactivesession = 1400; $this->session_life = $session_life; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $this->session_life = time() - $_SESSION['timeout']; if($this->session_life > $this->inactivesession) { session_destroy(); //header("Location: logout.php?msg=2"); return true; } else { return false; } } //$_SESSION['timeout'] = time() + $this->session_life; $_SESSION['timeout'] = time() + $this->inactivesession; //$_SESSION['timeout'] = time(); //return false; } /** * Destroy session data/Logout. */ function logout() { unset($_SESSION['LoggedIn']); unset($_SESSION['fullName']); unset($_SESSION['userName']); unset($_SESSION['userID']); unset($_SESSION['timeout']); session_destroy(); } /** * Connect to the Database * * @return true/false */ function connect() { $this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_password) or die("Unable to connect to MySQL"); mysql_select_db($this->db_name, $this->connection) or die("Unable to select DB!"); // Valid connection object? everything ok? if($this->connection) { return true; } else return false; } /** * Disconnect from the db */ function disconnect() { mysql_close($this->connection); } /** * Cleans a string for input into a MySQL Database. * Gets rid of unwanted characters/SQL injection etc. * * @return string */ function clean($str) { // Only remove slashes if it's already been slashed by PHP if(get_magic_quotes_gpc()) { $str = stripslashes($str); } // Let MySQL remove nasty characters. $str = mysql_real_escape_string($str); return $str; } /** * create a random password * * @param int $length - length of the returned password * @return string - password * */ function randomPassword($length = 8) { $pass = ""; // possible password chars. $chars = array("a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J", "k","K","l","L","m","M","n","N","o","O","p","P","q","Q","r","R","s","S","t","T", "u","U","v","V","w","W","x","X","y","Y","z","Z","1","2","3","4","5","6","7","8","9"); for($i=0 ; $i < $length ; $i++) { $pass .= $chars[mt_rand(0, count($chars) -1)]; } return $pass; } } ?> Login page: Code: [Select] <?php session_start(); require ('class/MathGuard.class.php'); require_once('class/LoginSystem.class.php'); $userip = $_SERVER['REMOTE_ADDR']; if(isset($_POST['Submit'])) { if((!$_POST['Username']) || (!$_POST['Password'])) { // display error message header('location: login.php?msg=1');// show error exit; } // ######## MatchGuard check ######## if (!MathGuard :: checkResult($_REQUEST['mathguard_answer'], $_REQUEST['mathguard_code'])) { //show_error ("Incorrect Security Code entered"); header('location: login.php?msg=3'); exit; } $loginSystem = new LoginSystem(); if($loginSystem->doLogin($_POST['Username'],$_POST['Password'],$userip)) { /** * Redirect here to your secure page */ header('location: view_articles.php'); } else { header('location: login.php?msg=2'); exit; } } /** * show Error messages * */ function showMessage() { if(is_numeric($_GET['msg'])) { switch($_GET['msg']) { //case 1: echo "Please fill both fields."; case 1: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Please fill in all fields!</p></div>'; break; //case 2: echo "Incorrect Username or Password!"; case 2: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Incorrect Username or Password!</p></div>'; break; //case 3: echo "Incorrect Security Code"; case 3: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Incorrect Security answer!</p></div>'; break; } } } /* function show_error($myError) { echo $myError; //stop executing script and display the form exit(); }*/ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <meta name="robots" content="noindex, nofollow" /> <link rel="stylesheet" type="text/css" href="css/login.css" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/supersleight.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".block").fadeIn(1000); $(".msg").fadeIn(1000); $('.msg').supersleight(); }); </script> </head> <body> <div id="wrap"> <?php showMessage();?> <div class="block"> <div class="head"> <h3>Login</h3><!--<a href="#">Forgot Password?</a>--> </div> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div class="body"> <div class="div-row"> <label for="username">Username</label><input type="text" id="Username" name="Username" maxlength="30" /> </div> <div class="div-row"> <label for="password">Password</label><input type="Password" id="Password" name="Password" maxlength="30" /> </div> <div class="div-row"> <?php MathGuard::insertQuestion(); ?> </div> <div class="send-row"> <button id="login" value="Login" type="submit" name="Submit"></button> </div> </div> </form> </div> </div> </body> </html> Make pages secure include: Code: [Select] <?php session_cache_expire(240); session_start(); require('./class/LoginSystem.class.php'); $loginSys = new LoginSystem(); /** * if not logged in goto login form, otherwise we can view our page */ if(!$loginSys->isLoggedIn()) { header("Location: ./login.php"); exit; } $sessionTime = new LoginSystem(); if($sessionTime->sessionTimer()) { header("Location: ./logout.php?msg=2"); exit; } ?> Logout page: Code: [Select] <?php session_start(); require('class/LoginSystem.class.php'); $loginSys = new LoginSystem(); $loginSys->logout(); function showMessage() { if(is_numeric($_GET['msg'])) { switch($_GET['msg']) { case 1: echo '<div class="msg" style="border:1px; border-color:#8be57e; background:#b4efab; color:#337129;"><img src="images/icons/succes.png" alt=""/><p>You have logged out successfully.</p></div>'; break; case 2: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Due to inactivity your session has expired.</div>'; break; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <meta name="robots" content="noindex, nofollow" /> <link rel="stylesheet" type="text/css" href="css/login.css" /> <link rel="stylesheet" type="text/css" href="css/ui.dialog.css" /> <style type="text/css"> body{ background-image: none; } </style> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/supersleight.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".block").fadeIn(1000); $(".msg").fadeIn(1000); $('.msg').supersleight(); }); </script> </head> <body> <div id="wrap"> <?php showMessage();?> <div class="block"> <div class="head"> <h3>Logged Out</h3> </div> <div class="body"> <p align="center"><font color="#000000"><b>Redirecting to the 'Login' page in <span id="seconds" style="color:#ff0000;">10</span> seconds.</b></font></p> <script language="JavaScript"> var seconds = 10; setInterval( function(){ if (seconds <= 1) { window.location = 'http://domain.tld/cms/login.php'; } else { document.getElementById('seconds').innerHTML = --seconds; } }, 1000 ); </script> <br><br> <p align="center">If you are not redirected, go straight to the <a href="login.php"><font size="3" color="blue"><b>Login</b></font></a> page.</p> </div> </div> </div> </body> </html> MathGuard class (works fine and I have not changed anything in this file) Code: [Select] <? class MathGuard { /** A main hashing function: concat of user's answer, hour and the additional prime number (default 37) */ function encode($input, $prime) { return md5($input.date("H").$prime); } /** This function generates the hash code from the two numbers * @param $a first number * @param $b second sumber * @param $prime additional number to encode with * */ function generateCode($a, $b, $prime) { $code = MathGuard::encode($a + $b, $prime); return $code; } /** This function checks whether the answer and generated security code match * @param $mathguard_answer answer the user has entered * @param $mathguard_code hashcode the mathguard has generated */ function checkResult($mathguard_answer, $mathguard_code, $prime = 37) { // echo("prime; $prime, $mathguard_answer"); $result_encoded = MathGuard::encode($mathguard_answer, $prime); if ($result_encoded == $mathguard_code) return true; else return false; } /** this function inserts the two math term into your form, the parameter is optional */ function insertQuestion($prime = 37) { //default prime is 37, you can change it when specifying the different parameter $a = rand() % 10; // generates the random number $b = rand() % 10; // generates the random number $code = MathGuard :: generateCode($a, $b, $prime); echo ("<label for=mathcheck>Security: $a + $b =</label> <input type='input' name='mathguard_answer' size='2' maxlength='4' /><input type='hidden' name='mathguard_code' value='$code' />"); } /** this function returns math expression into your form, the parameter is optional * quite simmilar to insertQuestion, but returns the output as a text instead of echoing */ function returnQuestion($prime = 37) { //default prime is 37, you can change it when specifying the different parameter $a = rand() % 10; // generates the random number $b = rand() % 10; // generates the random number $code = MathGuard :: generateCode($a, $b, $prime); return ("<label for=mathcheck>Security: $a + $b =</label> <input type='input' name='mathguard_answer' size='2' maxlength='4' /><input type='hidden' name='mathguard_code' value='$code' />"); } } ?> edit: removed domain name Hi, I have sessions and cookies for my website with PHP 7.2 version. But now and again, it logs me out quickly. Sometimes after 10 minutes inactivity, other times it doesn't, or even sometimes on clicking a link on the site. I can't tell if it is the browsers settings which I changed, but made no difference. Can anybody see a problem with my sessions, if that is set up wrong and if it is the reason as to why I am getting logged out of my site a lot without logging out? htaccess Header always edit Set-Cookie (.*) "$1; SameSite=Strict" php.ini session.name = __MySession session.save_path = /path-to-sessions session.hash_function = sha512 session.gc_maxlifetime = 3600 session.gc_probability = 1 ; session.gc_divisor = 100 session.cookie_lifetime = 0 session.use_only_cookies = 1 session.use_trans_sid = 0 session.cookie_secure = 1 session.use_strict_mode = 1 session.cookie_httponly = 1 session.use_cookies = 1 session.referer_check = http://www.my-domain.com/ session.cache_limiter = nocache sessions function <?php function mySiteSession() { $session_name = '__MySession'; $cookie_domain = "www.my-domain.com"; if (strpos($_SERVER['REQUEST_URI'], 'secured-area')) { $cookie_path = "/secured-area/"; $saved_path_location = '/path-to-sessions'; ini_set('session.save_path', $saved_path_location); } else { if (strpos($_SERVER['REQUEST_URI'], 'contact-us-now') && !strpos($_SERVER['REQUEST_URI'], 'secured-area')) { $cookie_path = "/contact-us-now/"; $saved_path_location = '/path-to-sessions'; ini_set('session.save_path', $saved_path_location); $max_life_time_seconds = 3600; $_SESSION['created'] = time(); $session_life_time_seconds = time() - $_SESSION['created']; if ($session_life_time_seconds > $max_life_time_seconds) { session_destroy(); session_unset(); } } else { $cookie_path = "/secured-area/"; $saved_path_location = '/path-to-sessions'; ini_set('session.save_path', $saved_path_location); } } $cookie_secure = false; // website is not live and no https yet $cookie_httponly = true; $cookieParams = session_get_cookie_params(); session_set_cookie_params($cookieParams["lifetime"], $cookie_path, $cookie_domain, $cookie_secure, $cookie_httponly); session_name($session_name); secureSession(); session_write_close(); $cleanSession = @secureSession(); if (!$cleanSession) { session_regenerate_id(true); secureSession(); } session_regenerate_id(true); } function secureSession() { if (isset($_COOKIE[session_name()]) && preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $_COOKIE[session_name()])) { session_start(); } else if (isset($_COOKIE[session_name()])) { unset($_COOKIE[session_name()]); session_start(); } else { session_start(); } } ?> Web Page Layout <?php ob_start(); // some pages have this but not all mySiteSession(); // my sites code and html ob_flush(); // some pages have this but not all ?> I hope that this is enough information, as I am not sure how to get to the bottom of this. Edited February 10, 2019 by Cobra23I have created a login form. I am sending values through Ajax for form validation. However, I am having problem with the code that I am unable to store values in Sessions & Cookies.
I have added a "Remember me" checkbox into login form. I want to validate Boolean value using Javascript Checked property and send the data to PHP for validation.
If user clicks on remember me checkbox then the data should be stored in either Sessions & Cookies. If it is not checked then data should be stored only in Sessions. I am posting here my login form code, Ajax code & PHP code.
Could you guys help me to point out my mistake what I am doing wrong in this code?
Login Form:
<input type="checkbox" id="cb" name="cb"> <label for="cb">Remember me</label>Ajax Code: function login(){var e = _("email").value; var pass = _("password").value; var cb = _("cb").value; if(e == "" || pass == ""){ _("status").innerHTML = "Please fill out the form"; } else { _("loginbtn").style.display = "none"; _("status").innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "handlers/login_handler.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "login_failed"){ _("status").innerHTML = "Login failed, please try again."; _("loginbtn").style.display = "block"; } else { window.location = "message.php?msg=Hello "+ajax.responseText; } } } ajax.send("e="+e+"&pass="+pass+"&cb="+cb); } }PHP Code: $cb = cleanstr($_POST['cb']); if(isset($cb) && ($cb == true)) { // IF USER CLICKED ON REMEMBER ME CHECKBOX CREATE THEIR SESSIONS AND COOKIES $_SESSION['userid'] = $db_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_pass; setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("pass", $db_pass, strtotime( '+30 days' ), "/", "", "", TRUE); // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE id='$db_id' LIMIT 1"; $query = mysqli_query($con, $sql); echo $db_username; exit(); } else { // IF USER HAS NOT CLICKED ON REMEMBER ME CHECKBOX CREATE THEIR SESSIONS ONLY $_SESSION['userid'] = $db_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_pass; // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE id='$db_id' LIMIT 1"; $query = mysqli_query($con, $sql); echo $db_username; exit(); } hi phpfreaks Recently I tryed to create a login for my website and a logout using sessions. The problem I have is: Whenever I log in I will be going to the homepage of the website. My session will be set and everything works fine. Now when I log out my session will be unset and destroyed. The problem is, is that whenever I go back in history I can still see my homepage. When I refresh that page the browser asks the user to resend it's information (probably because it has to do with using post in my login template). b.t.w. is it a bad thing to use request and a .htaccess file for my login form? So whenever a user logs in -> logs out -> goes back in history -> refreshes -> resend information the user is not asked to answer any account and password information to get itself logged in again. This troubles me for quite a while now ! Here are the pages I use to login, logout and show the homepage: Login.php: Code: [Select] <?php class Handler_Login extends Action_Handler { function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { if ($this->session->check_session() == false) { $password = $_POST['password']; $username = $_POST['username']; $login = $this->dbh->Login($username, $password); if ($login == true) { $this->session->set('username', $username); $this->view->displayHome(); $this->view->display(); } else { echo "you are not logged in"; } } else { $this->view->displayHome(); $this->view->display(); } } } ?> Logout.php: Code: [Select] <?php class Handler_Loguit extends Action_Handler { function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { $this->session->stopSession(); $this->view->displayLogin(); $this->view->display(); } } ?> Home.php: Code: [Select] <?php class Handler_home extends Action_Handler { public function __construct($action_handle) { parent::construct($action_handle); $this->action = $action_handle; } function secured_handler() { if ($this->session->check_session() == false) { $this->view->displayLogin(); $this->view->display(); } else { $this->view->displayHome(); $this->view->display(); } } } ?> Session.php: Code: [Select] <?php class Session { function __construct() { if(!isset($_SESSION)) { session_start(); } } function set($name, $value) { $_SESSION[$name] = $value; } function get($name) { return $_SESSION[$name]; } function stopSession() { unset($_SESSION); session_destroy(); } function check_session() { if(isset($_SESSION['username']) && !empty($_SESSION['username'])) { return true; } else { return false; } } } ?> view.php: Code: [Select] <?php class view { private $tpl; function __construct() { } function displayStatus() { $status = file_get_contents("templates/status.tpl"); $this->tpl = str_replace("%content%", $status, $this->tpl); } function displayLogin() { $this->tpl = file_get_contents("templates/login.tpl"); } function displayHome() { $this->tpl = file_get_contents("templates/home.tpl"); } function display() { echo $this->tpl; } } ?> now what I'm trying to do is: whenever the user goes back in history after being logged out, the page should be redirected to the login page. I have no idea how I would accomplish this. I know it has got something to do with my login.php but I can't really make it redirect to itself since it will then most possibly start an endless loop of redirecting. I'm using templates to display my pages, if neccesary I will post them too, Thanks for your support and I hope this issue will get solved Hi! Having a lot of fun dusting off the coding and putting together a site with PHP, CSS, and jQuery. I've run into one problem that I can't get past though. I implemented jQuery History to use hashtags to maintain browser back/forward buttons and linkability of the site (and not reload header and footer when updating content). The main purpose of the site is to showcase photography that's hosted on Flickr. I've got this working well using Slickr. I have the Slickr code to load my galleries sets in a file called 'pictures.php' which is loaded fine into #page_content using a link to #pictures. The problem arises when I click on a gallery/set: I get taken back to the default view of the site without any hashtage because Slickr requires a link using parameters, so: www.myexamplesite.com/#pictures becomes www.myexamplesite.com/index.php?id=72157626067797650&p=1 As you can see, since it loses the hashtag, I am no longer looking at the right page. Does anybody have any ideas on how I can specify both the hashtag and the parameter? Cheers! I have the below code to open contents in a div or modal window and at the same time showing the url that matches the specified page which works as expected, no problems rising:
$(document).ready(function(){ ///////LINK in a Div//////// $('#all').delegate('a.img-lnk, a.txt-lnk', 'click', function(){ $('#main').empty(); var page = $(this).attr('id'); var pageurl = $(this).attr('data-seo'); $('#main').load("../"+ page + ".php"); window.history.pushState('','',pageurl); }); ///////LINK in a Modal Window//////// $('#all').delegate('a.pop-lnk', 'click', function(){ var poppage = $(this).attr('id'); var popurl = $(this).attr('data-seo'); $('#popup').load("../char-inf/"+ poppage + ".php"); window.history.pushState('','',"/char-inf/"+ popurl); }); $('body').delegate('.hide-it', 'click', function(){ $('.hide-it').hide(); $('#popup').empty(); window.history.back(); }); });Problem: If I give you a url of a link in my page e.g. www.example.com/test1 and paste it in your browser the test1 page will open normally, BUT after that if you navigate to page test2 then the new url becomes www.example.com/test1/test2. Is there a way to turn the url at its normal state which would be www.example.com/test2? Is there a way to change the url in the code below using window.history.pushState dynamically to match the "page" variable?
$(document).ready(function(){ $('#all').delegate('a.pop-lnk', 'click', function(){ var page = $(this).attr('id'); $('#popup').load("../folder/"+ page + ".php"); window.history.pushState('','','/page'); }); }); Edited by Pavlos1316, 18 November 2014 - 03:58 PM. A friend of mine is looking at relaunching a site he used to run and I am going to try to persuade him to move over to a dynamic site. The site is a Football Clubs history site and contains around 2,000 games and several hundred players. The obvious advantage of a dynamic site is that even the bits I just mentioned run to around 2,500 static pages, which could be reduced to just 2 pages if dynamically driven. I am fairly confident that I can do the conversion, but there is one thing that I already know I may struggle with and that is the page which shows game, births and deaths on this day in history. A rough example (using a very heavy Javascript code) can be found at http://follyball.co.uk/jeff/. In a simplified form (ignoring for now the foreign keys to relationships that these tables actually have) there will be two tables GAMES game_id | date | competition | opponent | score | attendance PLAYERS player_id | surname | firstname | date of birth | date of death What I would be looking for is a way to take todays date, and find any corresponding records in games.date, players.date of birth, players.date of death on the same date in previous years. This would be simple to do as three different queries but as I would like to actually mix the three and show them in date order, I would like to do it in one query, presumably using UNIONS. On top of this, I would also like a slightly different output for each different set, for example, if it was a game I would like year, competition, opponent, score, attendance, Whereas if it is a players birth or death, I would like it to show something like firstname surname was born in year Before I go delving too deep into how it may be done, I would like to know if it can be done! I cannot see why it would not be able to generate this but if it is going to be way out of my ability, then I will look for another option! Thanks in advance Steve Customers can view transaction history for approved and declined transactions (the reason for the decline should be included). Transactions are logged with their transaction reference numbers and status. I am trying to create a order history page. I want it to look something like this: Ordernumber: 12 Products: Product 1 Product 2 Product 3 Product 4 Total: xx Ordernumber: 13 Products: Product 5 Product 6 Total: xx and so on. I have a recordset which get the ordernumbers from my database and i have another recordset which get the products (this recordset has a WHERE clause which is used to get the products associated with its ordernumber. Code: [Select] mysql_select_db($database_lol, $lol); $query_ono = "SELECT DISTINCT ordre.ono FROM ordre WHERE ordre.bruker='{$_SESSION['MM_Username']}'"; $ono = mysql_query($query_ono, $lol) or die(mysql_error()); $row_ono = mysql_fetch_assoc($ono); $totalRows_ono = mysql_num_rows($ono); mysql_select_db($database_lol, $lol); $query_history = "SELECT ordre.vare FROM ordre WHERE ordre.ono='{$row_ono['ono']}'"; $history = mysql_query($query_history, $lol) or die(mysql_error()); $row_history = mysql_fetch_assoc($history); $totalRows_history = mysql_num_rows($history); This is the recordsets. this is my table: +-------+---------------------+------+ | ID | vare | ono | +-------+---------------------+------+ | 1 | Product 1 | 12 | | 2 | Product 2 | 12 | | 3 | Product 3 | 12 | | 4 | Product 4 | 12 | | 5 | Product 5 | 13 | | 6 | Product 6 | 13 | +-------+---------------------+------+ So my question is: How do i do this? list all the records i mean. Thanks Like many parents, I'm challenged with keeping my kids from browsing the evil parts of the internet. My son is 11 and my wife caught him deleting IE history the other day. The computer he uses is a Windows 8.1 laptop, and it is not Pro. How can i let him use internet explorer on his own user but keep him from tampering with any of the history ( or settings for that matter)? Is there a better solution? I found some internet history logging software online, but I didn't feel comfortable with the source, and fear it may contain viruses or other malware. im testing the following script and it wont send 1 2 3 until the script has finished executing. What can i do to flush the buffer after every echo statement?? <?php echo "1"; ob_flush();flush(); sleep(5); echo "2"; ob_flush();flush(); sleep(5); echo "3"; ob_flush();flush(); ?> i am trying to set user status as offline when user close browser but i am facing a problem ... i am calling a function when body unload which will set guest user status to "0" when user close the browser but it not working ... it execute php before function is called.. any idea why this is happening ...please help it's making me crazy I'd like to use an application that's not browser based, on Internet Explorer. I've read somewhere that this is possible with a PHP script, but which one? If you can get me on the right track, I'd really appreciate it. Cheers. I got a log-in form with database, it only logs if such username and password exists. I was told that if i wanna make a log-out button once logged-in, i need to add sessions to my code and idk how.. this is my code that checks if username/password exists, and if so it lets u log in, if not it displays a msg: if(isset($_POST['loginsubmit'])){ if($username !="" && $password !="") { ///////////////////////////////Check for username/pass in database//////////////////////////// $nameexists = false; $passexists = false; $result = pg_query("SELECT name FROM duom WHERE name='".$username."'"); while ($row = pg_fetch_array($result)) { if($row['name'] != ""){ $nameexists = true; } } if($nameexists) { $result = pg_query("SELECT pass FROM duom WHERE name='".$username."'"); while ($row = pg_fetch_array($result)) { if($row['pass'] == $password){ $passexists = true; echo "Prisijungimas pavyko, jusu vartotojo vardas - ".$username.""; include"loggedinform.php"; } else { echo "Slaptazodis netinka!"; } /////////////////Starts session if password is correct//////////////////////////////////////////// if ($passexists){ //Here i want it to start the session if password is correct } ////////////////////////////////////////////////////////////////////////////////////////////////////////// } } else { echo "Tokio vartotojo nera!"; } ////////////////////////////////////////////////////////////////////////////////////////////////////////// } else { echo "Uzpildykite visus duomenys!"; } } Cant i just make smth like this? if ($passexists){ session_start(); } hey i think i may have stored session variables incorrectly Code: [Select] $_SESSION['tel'] = $_GET['Lat']; $_SESSION['Lon'] = $_GET['Lon']; $_SESSION['Lat'] = $_GET['Lat']; is what i used to set the session variables with the data i then enter these into a table and they enter the correct information but two pages down the line i try to access them however i just get undefined variable when i set the variable is equal to the session. Code: [Select] $MyLon = $_SESSION['Lon']; $MyLat = $_SESSION['Lat']; the following is the errorr Quote Notice: Undefined index: Lat in Hi, is two people or more sitting on the same local network and sharing the same public ip address will have the same session if they browse all of them into the same website or same php script that create session ?
Edited by Issam, 16 November 2014 - 05:18 PM. Hi guys, I have come across a problem when working with session data, I have been storing data from a textarea in a session, but the problem is when I retrieve the data and display it back in a textarea or to mysql it saves the carriage returns and line breaks as \r\n not converting it to actual line breaks. e.g saving the following from a text area; Line 1 Line 2 Line 3 will actually show as: Line 1 \r\nLine 2 \r\nLine3 How do I get it to show properly as intended? I have tried str_replace('\r\n', '\n'); with double and single quotes any helpful suggestions would be much appreciated. Thanks.. |