PHP - Bullet Proof Sessions Not Working
I have been following an article on creating bullet proof sessions but I'm having problems with session variables i'm creating getting destroyed
I call the session_start() like this
SessionManager::sessionStart('MySession', 0, '/', 'localhost');But when i try to add new session vars, i think the preventHijacking() function is is getting called for some reason and it wipes out the session and creates a new one. Any ideas how I can get this to work? Here is the link http://blog.teamtree...tproof-sessions And here is the complete code class SessionManager{ static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null) { // Set the cookie name session_name($name . '_Session'); // Set SSL level $https = isset($secure) ? $secure : isset($_SERVER['HTTPS']); // Set session cookie options session_set_cookie_params($limit, $path, $domain, $https, true); session_start(); // Make sure the session hasn't expired, and destroy it if it has if(self::validateSession()) { // Check to see if the session is new or a hijacking attempt if(!self::preventHijacking()) { // Reset session data and regenerate id $_SESSION = array(); $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR']; $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT']; self::regenerateSession(); // Give a 5% chance of the session id changing on any request } elseif(rand(1, 100) <= 5) { self::regenerateSession(); } } else { $_SESSION = array(); session_destroy(); session_start(); } } static protected function preventHijacking() { if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent'])) return false; if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) return false; if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) return false; return true; } static function regenerateSession() { // If this session is obsolete it means there already is a new id if(isset($_SESSION['OBSOLETE'])) return; // Set current session to expire in 10 seconds $_SESSION['OBSOLETE'] = true; $_SESSION['EXPIRES'] = time() + 10; // Create new session without destroying the old one session_regenerate_id(false); // Grab current session ID and close both sessions to allow other scripts to use them $newSession = session_id(); session_write_close(); // Set session ID to the new one, and start it back up again session_id($newSession); session_start(); // Now we unset the obsolete and expiration values for the session we want to keep unset($_SESSION['OBSOLETE']); unset($_SESSION['EXPIRES']); } static protected function validateSession() { if( isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) ) return false; if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) return false; return true; } } Edited by AdRock, 24 October 2014 - 10:23 AM. Similar TutorialsHi, i am trying to add a very simple shopping cart script to my site, and the session is simply used to keep the contents of the shopping cart, yet its not working properly! Ok ignoring the layout issues with the cart here is the issues. Only two links to the same script First one is a link to the shopping cart with an action to add the item ID to it. http://www.heliuk.co.uk/index.php?n=pages/shop-cart-action&id=1&action=add This works, it adds the item to the session "cart", if that's successful it then shows the cart from the session. But if i just go to the shopping cart with no actions (so just to view it) it shows no items http://heliuk.co.uk/index.php?n=pages/shop-cart-action And what this is doing is checking it the cart is empty, if not show the cart, if it is then show nothing, which is what happening. But if you go back to the first link and add the item again, it is adding it on to the cart so the session is there and working? I don't understand what's happening! Here the shopping cart page. Code: [Select] <?php error_reporting(E_ALL ^ E_NOTICE); $product_id = $_GET["id"]; //the product id from the URL $action = $_GET["action"]; //the action from the URL //if there is an product_id and that product_id doesn't exist display an error message if($product_id && !productExists($product_id)) { die("Error. Product Doesn't Exist"); } switch($action) { //decide what to do case "add": $_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id break; case "remove": $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. break; case "empty": unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. break; } ?> <table class='main' cellspacing='1' cellpadding='4'> <tr class='head'> <td class='head' colspan='2'>HeliUK Shop - Your Shopping Cart</td> </tr> <tr> <td style='Text-align:left;' class='con1' colspan='2'> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <?php error_reporting(E_ALL ^ E_NOTICE); if($_SESSION['cart']) { //if the cart isn't empty //show the cart echo "<table border=\"1\" padding=\"0\" width=\"100%\">"; //format the cart using a HTML table //iterate through the cart, the $product_id is the key and $quantity is the value foreach($_SESSION['cart'] as $product_id => $quantity) { //get the name, description and price from the database - this will depend on your database implementation. //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection $sql = sprintf("SELECT title, description, price FROM items WHERE id = %d;", $product_id); $result = mysql_query($sql); //Only display the row if there is a product (though there should always be as we have already checked) if(mysql_num_rows($result) > 0) { list($name, $description, $price) = mysql_fetch_row($result); $line_cost = $price * $quantity; //work out the line cost $total = $total + $line_cost; //add to the total cost echo "<tr>"; echo "<td style=\"border-left-width: 1px; border-right-style: solid; border-right-width: 1px; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px\" width=\"145\">"; echo "<font face=\"Tahoma\" size=\"2\">$quantity</font></td>" ; echo "<td style=\"border-left-width: 1px; border-right-style: solid; border-right-width: 1px; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px\" width=\"693\">"; echo "<font face=\"Tahoma\" size=\"2\">$name</font></td>" ; echo "<td style=\"border-left-width: 1px; border-right-style: solid; border-right-width: 1px; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px\" width=\"162\">"; echo "<font face=\"Tahoma\" size=\"2\">$line_cost</font></td>" ; echo "<td style=\"border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px\">"; echo "<p align=\"center\"><a href=\"$_SERVER[PHP_SELF]?action=remove&id=$product_id\">" ; echo "<img border=\"0\" src=\"empty-cart.jpg\" width=\"24\" height=\"24\"></a></td>" ; echo "</tr>"; } } //show the total echo "<tr>"; echo "<td colspan=\"0\" align=\"right\">Total</td>"; echo "<td align=\"right\">$total</td>"; echo "</tr>"; //show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation echo "<tr>"; echo "<td colspan=\"0\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?action=empty\" onclick=\"return confirm('Are you sure?');\">Empty Cart</a></td>"; echo "</tr>"; echo "</table>"; }else{ //otherwise tell the user they have no items in their cart echo "You have no items in your shopping cart."; } ?> </table> </td> </tr> </table> <? //function to check if a product exists function productExists($product_id) { //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection $sql = sprintf("SELECT * FROM items WHERE id = %d;", $product_id); return mysql_num_rows(mysql_query($sql)) > 0; } ?> Hi, Im building a cart system and i have sessions for my cart and for my login, i find as soon as i login im getting a blank line added to my cart so im assuming its conflicting with my login session. This is my login session Code: [Select] $_SESSION['SESS_MEMBER_ID'] And my cart session is Code: [Select] $_SESSION['cart'] The code im using to display my cart is Code: [Select] $cart = $_SESSION['cart']; foreach( $cart as $key => $value){ echo "<td>" . $key . "</td><td><input type='text' value='" . $value . "'</td><td>Delete</td></tr>"; } What am i doing wrong here? any help would be appreciated. i have this while loop making my category links at the top of my page, but i still have the bullet after the last item. ive looked at other examples and CANNOT get mine to follow suit...help please? Code: [Select] $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query1 = "SELECT * FROM ob_category"; $data1 = mysqli_query($dbc, $query1); while($row=mysqli_fetch_array($data1)){ echo '<a href="viewlistings.php">' . $row['name'] . '</a> • '; } Hi everyone, I have this code to help me split a long paragraph into sentences and make every new sentence into a new line. Now i want to insert a bullet point, or a arrow in font of every line. I try many different approaches, but it didn't work. Can anyone point me to the right direction. Thanks for your help. Vanvoquan. Code: [Select] <table border="1" bordercolor="red"> <tr> <td> <p><?php echo stripslashes(str_replace('. ', '.<br />', $product_info['products_description'])); ?></p> </td> </tr> </table> Hi all, I am using cURL to return some information. I turn that information into a string. Unfortunately the string when printed has a bullet point. I've been playing with urldecode and rawurldecode to try and get rid of it but then I am left with =%3CLI%3EInvalid+expiry+date%3Cbr% When all I want is Invalid expiry date The messages may vary though, and there could be more than one bullet point. Any suggestions would be great. Thanks, Hi all, What is the best practice when using Sessions for guest users? I there. I am making a small game, either you or the computer win depending on who's life hit 0 first I am using sessions to hold the health values, however I need a little bit of help. How do I make it actually go down after each move until one hits 0? Here is my script and thanks in advance... Code: [Select] <?php session_start(); ?> <!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=utf-8" /> <title>Fighting Game</title> </head> <body> <form action="fighting_game.php" method="post"> <select name='move_choice' id='move_choice'> <option value='punch'>Punch</option> <option value='kick'>Kick</option> </select> <input type='submit' name='submitbtn' value='Continue' id='submitbtn'> </form> <div id='matchdiv'> <?php $_SESSION['ai_health'] = 100; $_SESSION['player_health'] = 100; $moves_ai = array("Computer punches you in the face!","Computer kicks you in the gut!"); $moves_player = array("You punch Computer in the face!","You kick computer in the gut!"); $move_damage = array(2,10); $move_dam_multiplier_player = array(rand(1,5),rand(5,10)); $move_dam_multiplier_ai = array(rand(1,5),rand(5,10)); if($_POST['submitbtn']){ $choice = $_POST['move_choice']; } if($choice == "punch"){ $total_dam_ai=($move_damage[0]*$move_dam_multiplier_ai[0]); $total_dam_player=($move_damage[0]*$move_dam_multiplier_player[0]); echo"$moves_player[1]"." Causing ".$total_dam_player." damage!<br>"; echo"Computers current health is ". ($_SESSION['ai_health']-$move_damage[0]*$move_dam_multiplier_player[0]); echo"<br>$moves_ai[1]"." Causing ".$total_dam_ai." damage!<br>"; echo"Your current health is ". ($_SESSION['player_health']-$move_damage[0]*$move_dam_multiplier_ai[0]); } elseif($choice == "kick"){ $total_dam_ai=($move_damage[1]*$move_dam_multiplier_ai[1]); $total_dam_player=($move_damage[1]*$move_dam_multiplier_player[1]); echo"$moves_player[1]"." Causing ".$total_dam_player." damage!<br>"; echo"Computers current health is ". ($_SESSION['ai_health']-$move_damage[1]*$move_dam_multiplier_player[1]); echo"<br>$moves_ai[1]"." Causing ".$total_dam_ai." damage!<br>"; echo"Your current health is ". $new_player_health=($_SESSION['player_health']-$move_damage[1]*$move_dam_multiplier_ai[1]); } if($_SESSION['ai_health']<=0 && $_SESSION['player_health']>=0){ echo"<br>Computer falls to the ground! He is knocked out! You win!"; } if($_SESSION['player_health']<=0 && $_SESSION['ai_health'] >= 0){ echo"<br>You fall to the ground! You are knocked out! You lose!"; } if($_SESSION['player_health']<=0 && $_SESSION['ai_health'] <=0){ echo"<br>You both fall to the ground! You are both knocked out! It's a draw!"; } ?> </div> </body> </html> I am new to SESSIONS and have a quick question about them. I want to use sesssions on my site but was wondering if they would work for the follow senario. Say a customer visits my url: http://www.mysite.com/?id=2 Now what i am doing is taking the id out of the URL using sessions and redirecting the user to http://www.mysite.com while my session ($_SESSION['id']) holds the value 2 in it. I have this working great, i believe it just looks better. Now if my customer decides to buy my product via paypal and is directed off my site while he/she is paying for said item on paypal when they return could i still use some of the information that i stored in my session?? I know i could use post and get to pass through paypal but unfortunately i have to use sessions for what i am trying to do. 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? Hello everyone, i'm new to php and i'm having hard time with sessions i'm trying to create a php file with a drop down menu and when you select an item from the drop down menu, you could retreve it from another page. for example: a1.php Code: [Select] <?php session_start(); if(isset($_POST['color'])) { $_SESSION['blue']='blue'; $_SESSION['red']='red'; $_SESSION['green']='green'; $_SESSION['orange']='orange'; } ?> <html> <body> <form id="shirt" method="post" action="a2.php"> <p> <select name="Size"> <option value="invalid">Select a size ...</option> <option value="blue">blue</option> <option value="red">red</option> <option value="green">green</option> <option value="orange">orange</option> </select> <br /> <input type="Submit" value="Add" name="Add" /> </p> </form> </body> </html> when the user chooses a color, it adds it to the session and then when the user clicks add, he is redirected to another page named a2.php which shows the color is added. if the user goes back to the original page and adds the same color again it shows that he added the item again: Color: ----------- Quantity: Red ----------- 2 a2.php Code: [Select] <?php session_start(); $item_id = $_GET[id]; $action = $_GET[action]; switch($action) { case "add": $_SESSION['color'][$item_id]++; break; case "remove": $_SESSION['color'][$item_id]--; if($_SESSION['color'][$item_id] == 0) unset($_SESSION['color'][$item_id]); break; case "empty": unset($_SESSION['color']); break; } ?> sorry if my question is not clear, any help is appreciated Thank You, So I'm trying to understand Sessions and how to store a variable within a session. What I want to t do, is start a session, check if variable is set, if not, set the variable. So with the code below, I start the session, i check the variable, if not set, i set it. But when i refrsh the page, it has the same session id but it didn't store the session variable from the previous load. Please, what am I missing? Code: [Select] <?php session_start(); echo "Session ID: ".session_id()."<br>"; echo "<br>chktrack P ".$_session['chktrack'].""; if ($_session['chktrack'] != 1){ $_session['chktrack']=1; } echo "<br>chktrack Post: ".$_session['chktrack'].""; echo "<br><a href='index.php'>Index</a>"; ?> Thanks in advance for your help. I haven't used sessions much until now, so this is probably due to my ignorance. I have a page that sets the session variable, and if I print from that page, the session variable (an array) is correct. But when I move to the next page, the same session variable has old, old, wrong data. The $arrAttendeeList is an exploded list from a textarea on a form turned into an array. Example: This page, let's call it page1.php, sets the variable: Code: [Select] <?php $_SESSION['arrAttendeeList'] = $arrAttendeeList; foreach ($_SESSION['arrAttendeeList'] as $temp) { print "$temp <br />"; } exit; ?> Results: Smithers, Waylon Bouvier, Selma Brockman, Kent But the next page, page2.php, when I call the same variable: Code: [Select] <?php foreach ($_SESSION['arrAttendeeList'] as $temp) { print "<br />$temp <br>"; } ?> I get yesterday's data: Smithers, Waylon Bouvier, Selma I've tried setting the session var to null but with the same results. Do I need to kill the session var before setting it to something else? Thanks - Hi all, If I have a list of session ids, is it possible to use this list to determine which session is no longer active? Seems like it should be do-able but can't find help on it so I'm kinda guessing its not! Thanks for any help, Michael 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(); } 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 Basically I am trying to make a login with sessions but its just not working. Can someone look and see for any errors in what I wrote or snippet suggestions? <?php //Start session session_start(); //Include database connection details require_once('config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $username = clean($_POST['username']); $password = clean($_POST['password']); //Input Validations if($username == '') { $errmsg_arr[] = 'Username missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: login.php"); exit(); } //Create query $qry="SELECT * FROM users WHERE AND username='$username' AND password='$password'"; $result=mysql_query($qry); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { //Login Successful session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['member_id']; $_SESSION['SESS_USERNAME'] = $member['username']; $_SESSION['SESS_EMAIL'] = $member['email']; $_SESSION['SESS_BETAKEY'] = $member['betakey']; $_SESSION['SESS_PIN'] = $member['pin']; session_write_close(); header("location: member-index.php"); exit(); }else { //Login failed $errmsg_arr[] = 'Username/Password Invalid'; $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: login.php"); exit(); } }else { die("Query failed"); } ?> 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 am in the process of opening my web site to the general public. Right now you have to have a username and password to see anything on the site. What I am looking to do is make it so anyone can see most things on the site. There will still be user accounts for things like admins and submitting ideas. What i have now is some links that look at the user rank and only show up if you are higher then a rank. What I need to do is make it so you don't need to log in to see the site but you still need to log in to edit things. Here is my sessions scrip Code: [Select] <?php session_start(); if(!$_SESSION['login']){ $_SESSION['rank']; $_SESSION['loggedinusername'] = $loggedinusername; $_SESSION['loggedinuseremail'] = $loggedinuseremail; header("location:login.php"); } $rank=$_SESSION['rank']; $loggedinusername=$_SESSION['loggedinusername']; $loggedinuseremail=$_SESSION['loggedinuseremail']; ?> How do I edit this so you are free to move around the site even if your not logged in? Thanks Hi, I have been looking at this code for hours and I can't figure out why the product name and quantity aren't transferring from treats.php to checkOut.php. I realize checkOut.php is extremely long but if I could get some help I would really appreciate it. In case you would want the link, it 's http://auntievics.com/treats.php |