PHP - Sessions Problem - Help!
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 Similar TutorialsHi, 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 Cobra23hello 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 ? I 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 Kind of a n00b here. on my main table (users) i named a column as "id", set it to auto-increment and as the primary key and created it like this: CREATE TABLE `users` ( `id` int(20) NOT NULL auto_increment, `full_name` varchar(200) collate latin1_general_ci NOT NULL default '', `user_name` varchar(200) collate latin1_general_ci NOT NULL default '', `user_pwd` varchar(200) collate latin1_general_ci NOT NULL default '', `user_email` varchar(200) collate latin1_general_ci NOT NULL default '', `activation_code` int(10) NOT NULL default '0', `joined` date NOT NULL default '0000-00-00', `country` varchar(100) collate latin1_general_ci NOT NULL default '', `user_activated` int(1) NOT NULL default '0', PRIMARY KEY (`id`) ) On the second table i created it like this: CREATE TABLE about_me ( about_id int NOT NULL, nick_name varchar(255), descript varchar(255), aim varchar(255), cell varchar(255), school varchar(255), music varchar(255), aspire varchar(255), City varchar(255), id int, PRIMARY KEY (about_id), FOREIGN KEY (id) REFERENCES users(id) ) I believe i imported the key correctly into my new table (about_me). Well I expected the id column to cascade down into this new table automatically which it didn't. RIght now if you log into my site and use the about me form, it posts to the new table "about_me" but it doesn't identify the user on the table with the primary key assigned to him from the first table (users). How do I use PHP sessions to identify the user by his/her id from the primary key in the table. I attached the whole site. The php for the log in is a prefab and I'm attempting to do the about me part on my own, I'm having alot of trouble with the whole sessions thing. I'm not really sure if I'm doing this correctly. so yeah any point in the right direction would be awesome! -Mike Hi, I have an admin area to update users detials etc.. I want this area to be secure so only admins can access it, Currently anyone and everyone can access the page. Code: [Select] <?PHP session_start(); /* really need to use a session variable to insure authorized to be here */ include ('db.php'); /* ======================================== 99% of the time it is better to put your query in a string. It makes debugging much easier ======================================== */ $query = "SELECT * FROM companies"; $result = mysql_query($query ) or die("SELECT Error: ".mysql_error()); $num_rows = mysql_num_rows($result); /* ======================================== I find it easier to locate problems if I indent code properly and drop out of PHP if there are large sections of html ======================================== */ ?> <br><br><br>There are <?PHP echo $num_rows; ?> removalspace users so far.<P> <table width="819" height="114"> <tr> <th>Company Name</th> <th>Contact Name</th> <th>Contact Number</th> <th>Email</th> <th>Address Line 1</th> <th>Address Line 2</th> <th>Location</th> <th>Postcode</th> <th>Basic Members</th> <th>Upgraded Users</th> <th>Company Logo</th> <th>Approved</th> </tr> <tr> <td colspan="6"></td> </tr> <?PHP while ( $row = mysql_fetch_array($result, MYSQL_ASSOC )) { ?> <tr> <td><?PHP echo $row['company_name']; ?></td> <td><?PHP echo $row['contact_name']; ?></td> <td><?PHP echo $row['phone']; ?></td> <td><?PHP echo $row['email']; ?></td> <td><?PHP echo $row['street1']; ?></td> <td><?PHP echo $row['street2']; ?></td> <td><?PHP echo $row['location']; ?></td> <td><?PHP echo $row['postcode']; ?></td> <td><?PHP echo $row['basicpackage_description']; ?></td> <td><?PHP echo $row['premiumuser_description']; ?></td> <?PHP /* ======================================== I presume you want to show the thumb version here ======================================== */ ?> <td><img src="images/thumbs/<?PHP echo $row['upload']; ?>" alt="logo"/></td> </tr> <tr> <td colspan="10"> <table> <tr> <td>Current level = <?PHP echo $row['approved']; ?></td> <td><a href="admin02.php?id=<?PHP echo $row['id']; ?>&level=1">Level 1 - Free</a></td> <td><a href="admin02.php?id=<?PHP echo $row['id']; ?>&level=2">Level 2 - Basic</a></td> <td><a href="admin02.php?id=<?PHP echo $row['id']; ?>&level=3">Level 3 - Premium</a></td> <td><a href="admin02.php?id=<?PHP echo $row['id']; ?>&level=0">Level 0 - Do Not Display</a></td> </tr> </table> </tr> <?PHP } echo "</table>"; ?></table> i know it's something like: <?php session_start(); if(isset($_SESSION " but dont know how to finish it correctly? " ?> Hi Something strange is happening and I can't understand it. A user can access an availability page of accommodation and book ita room, this works fine, and goes from availability to the booking form and back quite well, carrying the room id of the accommdation and room/s selected in a session. If they close the browser down and open the availability page again all the rooms are there as before, but when they select a room and go to the booking form the session of the room id and the rooms selected are empty. If I do a session destroy and open the browser up again everything works fine again. I have tried this in Chrome and Firefox and it seems to work fine Any help would be appreciated So I am trying to set my session length, but it doesn't seem to be working. session_set_cookie_params("84600"); session_start(); 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.. 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. i have two files in php both have the same code and the file is Code: [Select] <?php session_start(); $con = mysql_connect("l","root",""); // here localhost and password will be filled accordingly if (!$con) { die('Connection failu ' . mysql_error()); } mysql_select_db("student",$con); $fetch=mysql_query("SELECT * from student1") or die(mysql_error()); $row = mysql_fetch_array($fetch) or die(mysql_error()); sleep(10); echo "Name: ".$row[0]."</br>"; echo " Age: ".$row[1]."</br>"; echo " Address: ".$row[2]; mysql_close($con); ?> Now i have another file which has the same code as above except there is no sleep function used in it . Now when i run the file which is wothout sleep it displyas results in seconds however the file with sleep function takes it time. Now the problem is if i load the file woth sleep function first then its delayed nature is reflected in another file which is without sleep() i.e now the file without sleep is taking longer time to open. please explain all this and possible solution to this problem the other file is Code: [Select] <?php session_start(); $con = mysql_connect("localhost","root","instablogs"); if (!$con) { die('Connection failu ' . mysql_error()); } mysql_select_db("student",$con); $fetch=mysql_query("SELECT * from student1") or die(mysql_error()); $row = mysql_fetch_array($fetch) or die(mysql_error()); echo "Name: ".$row[0]."</br>"; echo " Age: ".$row[1]."</br>"; echo " Address: ".$row[2]."</br>"; mysql_close($con); ?> When using sessions, must there be a session_start() in each page for the browser to be considered part of the session? Can a user browse to a page without session_start() and still have that part of the original session that he/she began with?? session_save_path("/home/content/q/1/w/q1w2e3r4t5y6u7/html/tmp/"); session_start(); I have this at the head of my index page. I'd like to count how many files are in temp to find out how many users are online. After going to my index page, i checked how many users were online via the script I wrote and it said 1. I refreshed the page and it said 2. It went as high as 10 with each refresh and then I stopped because something isn't right. I checked my temp folder and there are 10 temp files. How can one page visitor start so many unique sessions? Is there a way to prevent this? I'm using the session start command with dual purpose. One, if a user loads the page. Secondly, to check if $_SESSION['active'] exists so I know this is a registered user. How can i limit the amount of sessions started by an unknown user and efficiently count how many files are in the temp directory? Hello, I would like to make a session which saves the input. To make this easier to understand i will explain my whole problem. I will have that image uploader: HTML: <input type="file" /......> <input type="submit".....> and some php behind it to upload the image. When the file will be uploaded, there will be the text if you want to continue to next page (other php file) to edit uploaded file. Now what i am asking you is: If the user clicks yes, i want the session to save name of uploaded image without extension and save it as variable, so i can use it on that another page and print it out. Thank you i have an upload form and a posting form on the same page. when you upload a file it is uploaded to the server. what i am then trying to do is add the name of the file to $_SESSION['attachment'] so i can use it later. When the user posts their form i want the session to be inserted into the database but the session always comes up empty. this is what happens when they upload their file Setting the session and moving the file: session_start(); $_SESSION['attachment'] = "EXAMPLE"; move_uploaded_file($_FILES['Filedata']['tmp_name'], "../attachments/" . time() . $_FILES['Filedata']['name']); and then when they submit their form(textarea) it uploads the contents to the database and the contents of the session aswell. Why is this session always empty? I have a simple php script that starts sessions. On every page, I include : if(isset($_SESSION['sessionname'])){ //The rest of the page } else { die("Not logged in"); } I always include the session start and always regenerate the session id after <?php. The code works fine withevery browser except for a certain version of Internet Explorer 8. Even though the browser does enable cookies, it doesn`t seem to allow the ones in my script. In fact, every time I change page, it ives the error message "Not logged in". I have tried it on two different compters with the exact same version of IE and the result was the same. Thank you for your time! Hi all, What is the best practice when using Sessions for guest users? 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(); } Hello everyone, By default when someone comes to my site, it is the unencrypted web page (http://www.mydomain.com). I recently purchased a ssl certificate so when a user logs in, their password is encrypted (Posted to https://mydomain.com). Once the form is posted, the session is set and the header("Location: http://www.mydomain.com"); function is executed to bring them back to the unencrypted version of the site. However, now when a user tries to login, my site seems to drop the session when the location is set to the unencrypted version of the site. How do sites go about using a secure login form and running on the regular version of the site? Thanks! weee |