I am using sessions on my website: www.itsasoycandle.com and I have members log-in to get a discount. I also, above the logo in the left column have WELCOME "Name" once they are logged in. I am storing a session variable:

$_SESSION['memfirst']=$row['firstname'];

when they log-in. Sometimes the customer name shows and sometimes it does not. I am also having trouble with the cart not giving the proper discount because it does not know they are a member. This is happening on and off throughout the session. For those who want to test, go to members and use my email address ==> matthewnewhart@hotmail.com as the user. Put anything in for the password (temporarily not checking). Go back to home page and then down the left column buttons and you will see that WELCOME MATTHEW is sometimes there and sometimes not. This is a big hmmmm. This left column is an include:

<?php include("lcol_inc.php"); ?>

which is global on all of my pages. All of the pages start with a session_start() at the top.

OK, my main question(s) is that I thought that a session was persistant and so were the variables. Why would PHP sometimes be able to read the variables and sometimes not. Do I have to create a table to store the session_id() and the variables that I need in that table to maintain stability, or is this a PHP issue? Do I have to pass the variables in all of the alt tags for every link ==> index.php?session=asdf82rhaksdf7823rhbals&memid=24&memfirst=MATTHEW etc...? If someone could explain or have further insite on this it would be greatly appreciated. I am having to refund our members because they have not been getting all of their discounts(ouch!) and it is costing me money(time and transaction cost). My pages are pretty long and I don't thing I could post the whole layout in a message. If pieces are needed, let me know.

    sessions are persistant, and so are the variables. you don't need to store the session id server-side - php does that for you - but you should make sure that it is stored client-side, i.e. that a cookie is set, or the session id is appended to ALL links and also in forms. php takes care of some links automatically, but will usually miss a few. cookies are by far easiest.
    if you use cookies, you should check on login whether the user is accepting them, and show an error message if not, otherwise they will wonder what is going on.
    your site is setting a PHPSESSID cookie okay, so it should work if you really are calling session_start() on every page.
    on which pages do you get errors?
    my guess would be, it's probably your browser cache playing tricks on you. make sure you are refreshing the page properly. possibly add a no-cache header, if the page changes often, or while you are developing it.
    still, it's always a good idea to take session management into your own hands - set the cookies yourself, and check that they have been set.

      I have thought about using session cookies and also setting cookies using JavaScript. My only issue with this is the search engine marketing aspect. Some search engines don't like sites that use cookies and your site gets listed as "this site uses cookies and your browser is not..." in the list (Google does this often). As for which pages this is not working, it seems to be irregular. Sometimes it works on a page and sometimes it doesn't. With setting the session cookie and/or testing to see if they can accept cookies, is that done on the PHP side or is it done using JavaScript? My guess is that it is done on the PHP side of script. I have not had these problems until recently. My host just upgraded to 4.3.2 from 4.2.?. I will investigate using session cookies. Is there a good resource for sessions on the net? The PHP Manual does a good job, but does not always get into depth with each example. Thanks.

        I'm having a similar problem...

        My friend and I have both used sessions before, but have recently undertaken a web development project and are using his machine as a temporary development server. The only problem is that cookies just arn't getting set. Needless to say this castrates our plan for a login system. (we really dont want get vars)

        We're relatively certain the problem is in the configuration of PHP (4.3.2) or Apache (we're running 2), because the same code works on another server. We've tried just about everything we can think of when it comes to the php.ini, but to no avail. Here's the session excerpt from our php.ini:

        session.save_handler = files
        session.save_path = C:\PHP\sessiondata
        session.use_cookies = 1
        ; session.use_only_cookies = 1
        session.name = PHPSESSID
        session.auto_start = 1
        session.cookie_lifetime = 0
        session.cookie_path = /
        session.cookie_secure = 0
        session.cookie_domain = xxx.xxx.xxx.xxx
        session.serialize_handler = php
        session.gc_probability = 1
        session.gc_divisor     = 100
        session.gc_maxlifetime = 1440
        session.bug_compat_42 = 1
        session.bug_compat_warn = 1
        session.referer_check =
        session.entropy_length = 0
        session.entropy_file =
        ;session.entropy_length = 16
        ;session.entropy_file = /dev/urandom
        session.cache_limiter = nocache
        session.cache_expire = 180
        session.use_trans_sid = 0

        note:

        session.cookie_domain is replaced by my friend's IP.

        Anyone?

          Another note: When trying to manually set a cookie with 'setcookie', the function reports success, but no cookie is recieved.

          I don't have as much experience with setcookie though, so here's the code:

          setcookie ("testcookie");

            I was just thinking... Do you have to use session_start() for each of the <?php (code) ?> sections within a single php page? My pages start out with a session_start() and that is it... Then I have some html table structure and text. Then I have php includes inside <td>'s. In the includes there is some more html and tables which further the layout, and then some <?php (code) ?>.

            Question: Does each of these <?php (code) ?> sections have to have a session_start()? or does the first one make the session vars available to the rest of the php code sections? If PHP pops in and out of PHP Code and process through some HTML does the session vars and other variables for that matter stay persistant? Example:

            <?php
            $x=1;
            if ($x=2) {?> Hello!
            <?php } else { ?> Bye!
            <?php } ?> That was interesting...
            <?php print $x; ?>
            

            I have seen several different coding styles and one was like this. There was a great disscussion on this board about coding styles where I have seen this example... Will $x still equal 1 in the last php code section or will it return a variable not defined error?

            I have all of the $_SESSION vars I am reading trapped like this:

            if (isset($_SESSION['memfirst'])) {
                print "WELCOME " . $_SESSION['memfirst'];
            }
            

            So if it is not set, it does not error out. Some comments on php variables and their persistancy between code segments and html would be helpful. I don't know if this is the issue or not. Will test though to see if putting session_start() in each section helps...

              Originally posted by Codewarrior123
              I'm having a similar problem...

              Codewarrior123,

              Here is my php info:

              session.auto_start Off Off
              session.bug_compat_42 On On
              session.bug_compat_warn On On
              session.cache_expire 180 180
              session.cache_limiter nocache nocache
              session.cookie_domain no value no value
              session.cookie_lifetime 0 0
              session.cookie_path / /
              session.cookie_secure Off Off
              session.entropy_file no value no value
              session.entropy_length 0 0
              session.gc_divisor 100 100
              session.gc_maxlifetime 1440 1440
              session.gc_probability 1 1
              session.name PHPSESSID PHPSESSID
              session.referer_check no value no value
              session.save_handler files files
              session.save_path /web/tmp /web/tmp
              session.serialize_handler php php
              session.use_cookies On On
              session.use_only_cookies Off Off
              session.use_trans_sid On On

              Ooops! Shows a little different. The first setting is for LOCAL and the second is for MASTER. That is the way my host has it set up. The only difference I can see is the domain and the use_trans_sid which sets the PHPSESSID in the headers of each page. So as I thought to circumvent having to use cookies. I understand both sides of the cookie argument. I for one would rather use cookies, but when you are marketing a website and some search engine's bot does not like the cookie, it can still index the site. Where as the suggestion above would always kick everyone off if they don't have cookies turned on. I in the game of making money and do not want to lose or turn away a single potential customer. That is why I have not started using cookies, yet. I have a new idea that may have to use cookies and am trying to figure out a way to control it using MySQL and PHP feeding hidden forms and JavaScript. Oh well, I guess it is back to the drawing board. Any further comments are welcome...

                You only need session_start() once at the start of the script and before any output normally.
                How are you setting the session variables?

                The $_SESSION var is a SUPERGLOBAL and is accessable by any part of your script and is available after the closing ?>, any global variable is the same other wise doing ?> html stuff <?php wouldn't work.

                HalfaBee

                  <?php
                    function form ()
                    {
                     print "<br><br>";
                        print "<form method=\"POST\" action=\"memlogin.php\">\n";
                        print "<table border=\"0\" cellpadding=\"3\"  cellspacing=\"0\" valign=\"top\" align=\"center\">\n";
                          print "<tr nowrap>\n";
                            print "<td nowrap class=\"f10pt\" align=\"right\"><b>User Name:</b></td>\n";
                            print "<td nowrap class=\"f10pt\" align=\"left\"><input name=\"username\" type=\"text\" size=\"50\"> (email address)</td>\n";
                          print "</tr>\n";
                          print "<tr nowrap>\n";
                            print "<td nowrap class=\"f10pt\" align=\"right\"><b>Password:</b></td>\n";
                            print "<td nowrap class=\"f10pt\" align=\"left\"><input name=\"password\" type=\"password\" size=\"25\"> (email pw)</td>\n";
                          print "</tr>\n";
                          print "<tr nowrap>\n";
                            print "<td nowrap class=\"f10pt\" align=\"center\" colspan=\"2\"><input name=\"submit\" type=\"image\" src=\"images/login.jpg\" border=\"0\" alt=\"Log-In\" value=\"submit\"></td>\n";
                          print "</tr>\n";
                        print "</table>";    		
                        print "</form>";    		
                    }
                  
                  if (!isset($_SESSION['mysession'])) {
                  $_SESSION['mysession'] = session_id();
                  }
                  $thissession=$_SESSION['mysession'];
                  
                    print "<div align\"center\">";
                  
                  if (!isset($_SESSION['member'])) {
                  //Member is not logged in - do form checks
                  if (!isset($_POST['username'])) {
                    // Log-In form has not been submited - echo form
                  		form();
                  } else {
                    // Log-In form submited - Check Form for Entry
                  		$errvalue=0;
                  		$errormsg="";
                  
                    $validEmail = "^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$";			
                  
                  		if (!isset($_POST['username'])) {
                      $errvalue=1;
                        $errormsg.="<br><br><span class=\"f12pt\"><b>Please Fill in a valid User Name (email address)!</b></span>";
                  		} else {
                  		  $uname=$_POST['username'];
                  		  if ($uname=="" | is_null($uname) | !eregi($validEmail, $uname)) {
                  			  $errvalue=1;
                  			  $errormsg.="<br><br><span class=\"f12pt\"><b>Please Fill in a valid User Name (email address)!</b></span>";
                  			}
                    }
                  
                  		if (!isset($_POST['password'])) {
                      $errvalue=1;
                      $errormsg.="<br><br><span class=\"f12pt\"><b>Please Fill in the Password!</b></span>";
                  		} else {
                      $upwd=$_POST['password'];
                      if ($upwd=="" | is_null($upwd)) {
                  	    $errvalue=1;
                  	    $errormsg.="<br><br><span class=\"f12pt\"><b>Please Fill in the Password!</b></span>";
                  			}
                    }
                  
                  		if (!$errvalue) {
                      // Entry OK check members.txt for username and password
                  			$userismem=0;
                  
                      #Set link to db...
                      $dbh=mysql_connect ("xxxxx.com", "xxxxxxx", "xxxxx") or die ('I cannot connect to the database because: ' . mysql_error());
                      #$dbh=mysql_connect () or die ('I cannot connect to the database because: ' . mysql_error());
                      mysql_select_db ("xxxxxxxxx");
                  
                      $result = mysql_query("SELECT memberid, firstname, loginname, loginpw, referaffil FROM members WHERE loginname='$uname'");
                  
                      if (mysql_num_rows($result)>0) {
                        #$upwdmdf=md5($upwd);
                        #if ($row['loginpw']==$upwd || $row['loginpw']==$upwdmdf) {
                          $userismem=1;
                          #Should be only 1 row
                          $row = mysql_fetch_array($result, MYSQL_BOTH);
                          $_SESSION['member']=$row['memberid'];
                          $memid=$_SESSION['member'];
                          $_SESSION['memfirst']=$row['firstname'];
                          #Set Affiliate if applicable
                          if(!isset($_SESSION['affil'])) {
                            if (!is_null($row['referaffil'])) $_SESSION['affil']=$row['referaffil'];
                          }
                  
                          #Need to see if there are any cart items and adjust price
                          mysql_free_result($result);
                  
                        	$thissession=$_SESSION['mysession'];
                          $result = mysql_query("SELECT * FROM carts WHERE cartid='$thissession'");
                          $count = 0;
                  
                          while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                            $itemcat=$row['itemid'];
                            $catprices = mysql_query("SELECT * FROM catprices WHERE itemid='$itemcat'");
                            $catrow = mysql_fetch_array($catprices, MYSQL_BOTH);
                            $pricetouse=2;
                  
                            if ($row['cotm']==1) {
                              $pricetouse=4;
                            }
                            $itemprice=$catrow[$pricetouse];
                            mysql_free_result($catprices);
                  
                            mysql_query("UPDATE carts SET itemamount='$itemprice', memberid='$memid' WHERE cuid=".$row['cuid']);
                            $count++;
                          }
                        #}
                      }
                  
                      mysql_free_result($result);
                  
                  		  if (!$userismem) {
                  	    $errvalue=1;
                  		  $errormsg.="<br><br><span class=\"f12pt\"><b>Your User Name and Password was not found in our database!<br>Please check your entries.  If you are not a member,<br>you can sign up here:</b></span><br><a href=\"joinclub.php\"><img src=\"images/signup.jpg\" border=\"0\" alt=\"Join Candle Club\"></a>";
                  		} else {
                        // User has succesfully logged in.
                        print "<br><br><span class=\"f14pt\"><b>You are logged in as a Candle Club Member!<br>All Items will have a 10% price reduction while you are logged in!<br><br>Thank You!</b></span>";
                        if ($count>0) print "<br><br><span class=\"f14pt\"><b>The Items in your cart will now reflect your 10% discount!</b></span>"; 
                        $errvalue=0;
                  		}
                  	  }
                  
                    if ($errvalue==1) {
                      print $errormsg;
                      form();
                  		} 
                  }
                    } else {
                     //Member is already logged in - echo status
                      print "<br><br><span class=\"f14pt\"><b>You are already logged in as a Member!<br><br>Thank You!</b></span>";
                    }
                  
                    print "<br><a href=\"index.php\"><img src=\"images/contshop.jpg\" border=\"0\" alt=\"Continue Shopping\"></a>";
                    print "</div>";
                  ?>
                  

                  I have xxxxx'd out the db connection stuff... I am setting the variables like above and using them like this:

                                    <?php
                                      $memfn=" ";
                  
                                  if (isset($_SESSION['memfirst'])) {
                                    $memfn.=$_SESSION['memfirst'];
                                  } 
                  
                                  print "Welcome" . $memfn;
                                ?>
                  

                  Both of these scripts are in the middle of a bunch of html. EVERY PAGE HAS A session_start(); AT THE TOP! No need to yell, sorry. I make sure this is there on every page. I have even re-itterated it on some of my script sections because they did not seem to want to grab the session vars without this:

                                          <?php 
                                            if (!isset($_SESSION['mysession'])) {
                                              $_SESSION['mysession'] = session_id();
                                            }
                                          	$thissession=$_SESSION['mysession'];
                  
                  

                  That code seemed to "wake up" the session to allow me to grab the rest of the variables...hmmm.

                    Originally posted by mnewhart
                    Some search engines don't like sites that use cookies and your site gets listed as "this site uses cookies and your browser is not..." in the list (Google does this often).

                    As a clarification, it's not the search engine that says this but the site being indexed; whoever wrote the site decided that serving up page saying "This site uses cookies and your browser is not..." to any clients that don't use cookies is an acceptable alternative to making the site work without them. Since Google's spider doesn't use cookies, it gets the error page, and that's what gets indexed

                      9 days later

                      Originally posted by Weedpacket
                      Since Google's spider doesn't use cookies, it gets the error page, and that's what gets indexed

                      Although I will often try to set cookies on other pages, I only insist on them on the login page. As Weedpacket rightly says, you will otherwise lock out search engines, not to mention people who, by default, have cookies turned off.

                      There's a good chance, if they've no pressing need to view your site, that they will simply leave and never come back.

                        Write a Reply...