PHP - Working With Multple Sessions
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. 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; } ?> 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. 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.. 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! 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 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 - 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 am makeing a forum and to post a new thread it has to check if the user is logged in, so i log into my website and i go to the post new topic but it says im not logged in here is the new_topic.php and also the login.php new_topic.php <?php session_start(); include_once "../scripts/connect_to_mysql.php"; // Connect to the database // Check to see if the user is logged in with session variables if (!isset($_SESSION['userpass']) || $_SESSION['userpass'] == "") { echo "Please log in..."; exit(); } else { // Assume they are a member because they have a password session variable set // Check the database to be sure that their ID, password, and email session variables all match in the database $u_id = mysql_real_escape_string($_SESSION['id']); $u_name = mysql_real_escape_string($_SESSION['username']); $u_email = mysql_real_escape_string($_SESSION['useremail']); $u_pass = mysql_real_escape_string($_SESSION['userpass']); $sql = mysql_query("SELECT * FROM myMembers WHERE id='$u_id' AND username='$u_name' AND email='$u_email' AND password='$u_pass'"); $numRows = mysql_num_rows($sql); if ($numRows < 1) { echo "ERROR: You do not exist in the system."; exit(); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Check to make sure the URL variables of "sid" and "title" are set if (!isset($_POST['forum_id']) || $_POST['forum_id'] == "" || !isset($_POST['forum_title']) || $_POST['forum_title'] == "") { echo "Important variables are missing"; exit(); } else { // Acquire the variables and proceed to show them a form for creating a new topic $forum_section_id = preg_replace('#[^0-9]#i', '', $_POST['forum_id']); $forum_section_title = preg_replace('#[^A-Za-z 0-9]#i', '', $_POST['forum_title']); } /////////////////////////////////////////////////////////////////////////////////////////////////// $sql = mysql_query("SELECT * FROM forum_sections WHERE id='$forum_section_id' AND title='$forum_section_title'"); $numRows = mysql_num_rows($sql); if ($numRows < 1) { echo "ERROR: That section deos not exist."; exit(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="style/style.css" rel="stylesheet" type="text/css" /> <title>Create New Topic</title> <script type="text/javascript" language="javascript"> <!-- function validateMyForm ( ) { var isValid = true; if ( document.form1.post_title.value == "" ) { alert ( "Please type in a title for this topic" ); isValid = false; } else if ( document.form1.post_title.value.length < 10 ) { alert ( "Your title must be at least 10 characters long" ); isValid = false; } else if ( document.form1.post_body.value == "" ) { alert ( "Please type in your topic body." ); isValid = false; } return isValid; } //--> </script> </head> <body> <?php include_once("template_header.php"); ?> <table style="background-color: #F0F0F0; border:#069 1px solid; border-top:none;" width="900" border="0" align="center" cellpadding="12" cellspacing="0"> <tr> <td width="731" valign="top"> <div id="breadcrumbs"><a href="http://www.webintersect.com">Web Intersect Home</a> ← <a href="http://www.webintersect.com/forum">Forum Home</a> ← <a href="section.php?id=<?php echo $forum_section_id; ?>"><?php echo $forum_section_title; ?></a></div> <h2>Creating New Topic In the <em><?php echo $forum_section_title; ?></em> Forum</h2> <form action="parse_post.php" method="post" name="form1"> <input name="post_type" type="hidden" value="a" /> Topic Author:<br /><input name="topic_author" type="text" disabled="disabled" maxlength="64" style="width:96%;" value="<?php echo $u_name; ?>" /> <br /><br /> Please type in a title for your topic he <br /><input name="post_title" type="text" maxlength="64" style="width:96%;" /><br /><br /> Please type in your topic body:<br /><textarea name="post_body" rows="15" style="width:96%;"></textarea> <br /><br /><input name="" type="submit" value="Create my topic now!" onclick="javascript:return validateMyForm();"/> <input name="fsID" type="hidden" value="<?php echo $forum_section_id; ?>" /> <input name="fsTitle" type="hidden" value="<?php echo $forum_section_title; ?>" /> <input name="uid" type="hidden" value="<?php echo $_SESSION['id']; ?>" /> <input name="upass" type="hidden" value="<?php echo $_SESSION['userpass']; ?>" /> </form> </td> <td width="189" valign="top"><div style=" width:160px; height:600px; background-color: #999; color: #CCC; padding:12px;"> <br /> <br /> <br /> <h3>Ad Space or Whatever</h3> </div></td> </tr> </table> <?php include_once("template_footer.php"); ?> </body> </html> login.php <?php // Start Session to enable creating the session variables below when they log in session_start(); // Force script errors and warnings to show on page in case php.ini file is set to not display them error_reporting(E_ALL); ini_set('display_errors', '1'); //----------------------------------------------------------------------------------------------------------------------------------- // Initialize some vars $errorMsg = ''; $email = ''; $pass = ''; $remember = ''; if (isset($_POST['email'])) { $email = $_POST['email']; $pass = $_POST['pass']; if (isset($_POST['remember'])) { $remember = $_POST['remember']; } $email = stripslashes($email); $pass = stripslashes($pass); $email = strip_tags($email); $pass = strip_tags($pass); // error handling conditional checks go here if ((!$email) || (!$pass)) { $errorMsg = 'Please fill in both fields'; } else { // Error handling is complete so process the info if no errors include 'scripts/connect_to_mysql.php'; // Connect to the database $email = mysql_real_escape_string($email); // After we connect, we secure the string before adding to query //$pass = mysql_real_escape_string($pass); // After we connect, we secure the string before adding to query $pass = md5($pass); // Add MD5 Hash to the password variable they supplied after filtering it // Make the SQL query $sql = mysql_query("SELECT * FROM myMembers WHERE email='$email' AND password='$pass' AND email_activated='1'"); $login_check = mysql_num_rows($sql); // If login check number is greater than 0 (meaning they do exist and are activated) if($login_check > 0){ while($row = mysql_fetch_array($sql)){ // Pleae note: Adam removed all of the session_register() functions cuz they were deprecated and // he made the scripts to where they operate universally the same on all modern PHP versions(PHP 4.0 thru 5.3+) // Create session var for their raw id $id = $row["id"]; $_SESSION['id'] = $id; // Create the idx session var $_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$id"); // Create session var for their username $username = $row["username"]; $_SESSION['username'] = $username; mysql_query("UPDATE myMembers SET last_log_date=now() WHERE id='$id' LIMIT 1"); //die($username); } // close while // Remember Me Section if($remember == "yes"){ $encryptedID = base64_encode("g4enm2c0c4y3dn3727553$id"); setcookie("idCookie", $encryptedID, time()+60*60*24*100, "/"); // Cookie set to expire in about 30 days setcookie("passCookie", $pass, time()+60*60*24*100, "/"); // Cookie set to expire in about 30 days $_SESSION['username'] = $username; } // All good they are logged in, send them to homepage then exit script //die($_SESSION['username']); $_SESSION['username'] = $username; header("location: index.php?user=$username;"); exit(); } else { // Run this code if login_check is equal to 0 meaning they do not exist $errorMsg = "Incorrect login data, please try again"; } } // Close else after error checks } //Close if (isset ($_POST['uname'])){ ?><!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" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <link href="style/main.css" rel="stylesheet" type="text/css" /> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <title>Log In</title> <style type="text/css"> <!-- body { margin-top: 0px; } --> </style></head> <body> <table width="400" align="center" cellpadding="6" style="background-color:#FFF; border:#666 1px solid;"> <form action="login.php" method="post" enctype="multipart/form-data" name="signinform" id="signinform"> <tr> <td width="23%"><font size="+2">Log In</font></td> <td width="77%"><font color="#FF0000"><?php print "$errorMsg"; ?></font></td> </tr> <tr> <td><strong>Email:</strong></td> <td><input name="email" type="text" id="email" style="width:60%;" /></td> </tr> <tr> <td><strong>Password:</strong></td> <td><input name="pass" type="password" id="pass" maxlength="24" style="width:60%;"/></td> </tr> <tr> <td align="right"> </td> <td><input name="remember" type="checkbox" id="remember" value="yes" checked="checked" /> Remember Me</td> </tr> <tr> <td> </td> <td><input name="myButton" type="submit" id="myButton" value="Sign In" /></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td colspan="2">Forgot your password? <a href="forgot_pass.php">Click Here</a> <br /></td> </tr> <tr> <td colspan="2">Need an Account? <a href="register.php">Click Here</a><br /> <br /></td> </tr> </form> </table> <br /> <br /> <br /> </body> </html> Hey Guys, Me again! Still working on this bloody database! Okay, so I have a site that people can add a record to a database. This record is filled using a form and the form contains an image that can be uploaded. This works fine. Then there's the ability to search a record based on a boolean search which displays a table with the record data and displays a thumbnail of the photo. This also works fine. Then I have a script that (once it's working) will allow you to edit the record. This is where I'm having issues. Here's my process for the form: User searches for the record by using a boolean search Search finds the record and displays a form containing the original values in the database User changes some parts of the original record using the form Form then updates the database with the new values The problem I'm having is with the photo function. If there's no photo attached, I was getting an error saying that the photo field could not be empty. So I used the following process: User searches for the record using edit.php Form is displayed using edit_process.php edit_process.php is posted to update.php that has conditions to check if the file upload field is empty or not If the field is empty, then it requires updatenophoto.php If the field has a new image, it uses updatephoto.php When I submit the form to the update.php script, it does nothing and gives me a blank page. Here's my code for each of the parts (hit the character limit, code in comments): 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, 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 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. Hi all, What is the best practice when using Sessions for guest users? So I am trying to set my session length, but it doesn't seem to be working. session_set_cookie_params("84600"); session_start(); How do you set a time limit on a session? hi im new to php i am making shopping cart i made a session variable to add products in cart when i run it gives this warning Notice: Undefined index: cart in C:\wamp\www\cart\public\views\layouts\shop.php on line 15 Notice: Undefined index: total_items in C:\wamp\www\cart\public\views\layouts\shop.php on line 16 Notice: Undefined index: total_price in C:\wamp\www\cart\public\views\layouts\shop.php on line 17 but when i click on add to cart it add product price and quanitity kindly help me my shop.php code is <head> <title> Shopping Cart</title> <link href="stylesheets/cool_style.css" media="screen" rel="Stylesheet" type="text/css" /> </head> <body> <h1> products</h1> <div class="cart"> <p><b> Shopping Cart</b></p> print_r($_SESSION['cart']); echo $_SESSION['total_items']; echo number_format($_SESSION['total_price'],2); </div> <hr /> </body> </html> and my index file is where i set session variables are include('db_fns.php'); include("cart_functions.php"); session_start(); if(isset($_SEESION['cart'])) // if change this conditon if(!isset($_SEESION['cart'])) it gives not warning but does not //add products to the cart it does not do anything { $_SESSION['cart']=array(); $_SESSION['total_items']=0; $_SESSION['total_price']=0.00; } $view=empty($_GET['view'])?'index':$_GET['view']; $controller='shop'; switch ($view){ case "index"; $products = find_product(); break; case "add_to_cart"; $id=$_GET['id']; $add_item=add_to_cart($id); $_SESSION['total_items']=total_items($_SESSION['cart']); $_SESSION['total_price']=total_price($_SESSION['cart']); header('Location: index.php'); break; case "update_cart"; break; case "checkout"; break; } if change this conditon if(!isset($_SEESION['cart'])) it gives not warning file run correctly with no warning but does not add products to the cart and does not do anything kindly help me please 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 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 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); ?> |