I am making a login system and such for a site, and I am having trouble with $SESSION variables. I still don't fully understand how they work, but i'm pretty sure session data doesn't reset when you refresh the page. I have a user panel 'box'/template element that gives the user options on what to do if they are logged in, but when the page refreshes, the $SESSION['uid'], which is what the site uses to find out info on the user, gets set to 1, when for example, it's suppossed to be 7, and thats what it was until the page refreshes. What's wrong? (EDIT)I Trimmed my code to only be the user panel php. The session does get started at the top of the page, and I have the database connections in a include at the top.

<?php
// Start user panel
// If logged in, begin gathering info.
if(isset($_SESSION['uid'])){
		// Get info on user from database where uid row in table is equal to session variable 'uid', set by the login.
		$finduser=@mysql_query("SELECT * FROM members WHERE uid=" . $_SESSION['uid'] . "");
		// Begin writing info.
		while($digit=mysql_fetch_array($finduser)){
			// Define username
			$myname = $digit['username'];
			// The number of movies the user has submitted, in query form.
			$mynumovies_query=@mysql_query("SELECT * FROM movies WHERE uid=" . $_SESSION['uid'] . "");
			// The number of movies the user has submitted.
			$mynumovies = mysql_num_rows($mynumovies_query);
			// Welcome the User With His/Her Username
			echo "Welcome, $myname<br><br>";
			// If the number of movies is one, the end of "You have Submitted NUM Movie" will be singular.
			if($mynumovies == 1){
				$ender = ".";
			}
			// If it's not equal to 1, the ending is plural.
			else{
				$ender = "s.";
			}
			// Echo out how many movies the user has submitted.
			echo "You have submitted $mynumovies Movie$ender<br>";
			// Echo a link to view their profile.
			echo "<a href=\"member?uid=$uid\" title=\"View Your Profile\">View My Profile</a><br>";
			// Echo a link to edit their profile.
			echo "<a href=\"profile\" title=\"Edit Your Profile\">Edit My Profile</a><br>";
			// Echo a link to submit a movie.
			echo "<a href=\"submit\" title=\"Submit a Movie\">Submit a Movie</a><br>";
			// Echo a link to edit their submissions.
			echo "<a href=\"submissions\" title=\"Edit, Delete, or View your Movie uploads\">My Submissions</a><br><br>";
			// Echo a link to logout.
			echo "Or <a href=\"logout\" onclick=\"return log_out();\" title=\"Logout Of AVP Showcase\">Logout</a>";	
		}
}
// If they aren't logged in and for some reason weren't re-directed, tell them they need to log in.
else{
	echo "You Are Not Logged In, Please <a href=\"login\" title=\"Log In To AVP Showcase\">Log In.</a>";
}
?></center></td></tr></table></td>
	<tr>

I think i'm not using sessions correctly? Do i have to set the UID session variable each time the page loads?

    Hi, on every page that you need to access a session, you will need to have:

    session_start();

    at the beginning of the page. And instead of:

    if(isset($_SESSION['uid'])) {

    I would use:

    if(session_is_registered("uid")) {

    If you have cookies enabled in your php.ini, using sessions stores the session id on a cookie on the users computer, and when you call it on a page it uses that id to retrieve their private data, which was set in your scripts, from the session file on your server. Also, what PHP version are you currently running?

    Peace,

    Ben

      O and one more thing, I think that the syntax on your While() statement is incorrect...

      You have:

      while($digit=mysql_fetch_array($finduser)){

      the single = sign is used to set $digit as something else. I think what you need is

      while($digit==mysql_fetch_array($finduser)){

      the double = sign is used for conditionals and means "is equal to". I may be just severely misunderstanding what you are trying to do, but that could be a major prob also.

        tawben wrote:

        I would use:

        if(session_is_registered("uid")) { 
        

        I wouldn't. It relies on register_globals being turned on which (a) is a security hazard, (b) degrades performance, (c) has been deprecrecated for some years now, and (d) will soon be gone from PHP entirely.

        $_SESSION is intended to replace it.

        while($digit=mysql_fetch_array($finduser)){

        I don't
        know why, but this is the conventional idiom for iterating through a recordset.
        Since there's only supposed to be one record (unless the "u" in "uid" means something other than what I'd expect), having an entire loop for it is
        somewhat redundant. It could just as easily have been written if($digit=...),
        but having just one '=' there looks even odder, so

        $digit = mysql_fetch_array($finduser);
        if($digit)
        {
        //...
        }

        ($digit's a funny name to use, incidentally).

        After that, addressing the original issue; yes. Each page has to have the session started before session variables can be used.

          I do have session_start() at the top of the page, and it still doesn't work. I switched the while() to a if(), and the same thing still happens. Here is my script from top to the bottom of the userpanel:

          <?php
          session_start();
          // If not logged in, redirect to login.
          if(!isset($_SESSION['uid'])){
          	header("Location: login");
          }
          ?>
          <?php
          // Start Hit Counter
          $c_ip = $HTTP_COOKIE_VARS["user_ip"];
          $counter_file = "scripts/count.txt";
          $counter_file_line = file($counter_file);  if(!$c_ip) {
          setcookie("user_ip", $REMOTE_ADDR, time()+360000);  $counter_file_line[0]++; 
          $cf = fopen($counter_file, "w+");
          fputs($cf, "$counter_file_line[0]");  fclose($cf); 
          } 
          elseif($c_ip != $REMOTE_ADDR){
          $counter_file_line[0]++;   $cf = fopen($counter_file, "w+");
          fputs($cf, "$counter_file_line[0]");
           fclose($cf);
          }
          // End Hit Counter
          ?>
          <?php
          // Include database connections.
          include("scripts/config.php"); 
          ?>
          <title>Association of Video Professionals Showcase - A Video Producers Portfolio</title>
          <head>
          <link rel="shortcut icon" href="favicon.ico"/>
          <link rel="stylesheet" href="scripts/scripts?sid=2" type="text/css"/>
          <script type="text/javascript" src="scripts/overlib.js"></script>
          <script type="text/javascript" src="scripts/scripts?sid=1"></script>
          <?php
          // Start Browser Check Using Sessions
          //If session variable browser is set, do nothing.
          if($_SESSION["browser"] == "checked"){
          }
          // Else, implemement jscript browser check.
          else{
          	$_SESSION["browser"] = "checked";
          	echo "<script type=\"text/javascript\">
          if(navigator.userAgent.indexOf('Firefox')!=-1){
          }
          else{
          	if(confirm('You are using a internet browser other than Firefox. It is recomended that you use Firefox to view this website, for some elements may show up incorrect or not function at all. Click Ok to get the newest version of Firefox, or click cancel to hide this prompt.')== true){
          		changehref('http://www.mozilla.com/en-US/firefox/');
          	}
          }
          </script>
          ";
          }
          // End browser check.
          ?>
          </head>
          <body id="html">
          <center><a href="http://avpshowcase.com/" title="Association of Video Professionals Showcase"><img src="images/header.png" alt="" border="0"/></a><br>
          <div class="menu_back"><table border="0" cellpadding="0" cellspacing="0" align="center">
          	<tr>
          		<td class="menu_left"></td>
          		<td class="menu_middle">
          			<a href="index" title="Go to the Home page"><img src="images/home.png" alt="Home" border="0" title="Go to the Home page"/></a>
          			<a href="movies" title="Go to the Movie list"><img src="images/movies.png" alt="Movies" border="0" title="Go to the Movie list"/></a>
          			<a href="submit" title="Submit a Movie"><img src="images/submit.png" alt="Submit" border="0" title="Submit a Movie"/></a>
          			<a href="submissions" title="Edit, Delete, or View Movies you have submitted"><img src="images/submissions.png" alt="My Submissions" border="0" title="Edit, Delete, or View Movies you have submitted"/></a>
          			<a href="profile" title="Edit your Profile information"><img src="images/profile.png" alt="Profile" border="0" title="Edit your Profile information"/></a>
          			<a href="members" title="View a list of all registered Members and their Profiles"><img src="images/members.png" alt="Members" border="0" title="View a list of all registered Members and their Profiles"/></a>
          			<a href="register" title="Register as a Member"><img src="images/register.png" alt="Register" border="0" title="Register as a Member"/></a>
          		</td>
          		<td class="menu_right"></td>
          	</tr>
          </table></div>
          <!-- START MAIN TABLE asset -->
          <table cellpadding="0" cellspacing="5" border="0" align="center">
          <tr>
          <td>
          <div style="height:100%;">
          <!-- START small TABLE asset -->
          <table cellpadding="0" cellspacing="0" border="0">
          	<tr>
          		<td class="small_top"><center><br><?
          	if(isset($_SESSION['uid'])){
          		echo "User Panel";
          	}
          	else{
          		echo "Please Log In";
          	}
          ?></center></td>
          	</tr>
          		<td class="small_middle"><table align="center" border="0" cellpadding="0" cellspacing="0" width="140" height="100%"><tr><td><center><?php
          // Start user panel
          // If logged in, begin gathering info.
          if(isset($_SESSION['uid'])){
          		// Get info on user from database where uid row in table is equal to session variable 'uid', set by the login.
          		$finduser=@mysql_query("SELECT * FROM members WHERE uid=" . $_SESSION['uid'] . "");
          		// Fetch the mysql data
          		$digit=mysql_fetch_array($finduser);
          		// Begin writing info.
          		if($digit){
          			// Define username
          			$myname = $digit['username'];
          			// The number of movies the user has submitted, in query form.
          			$mynumovies_query=@mysql_query("SELECT * FROM movies WHERE uid=" . $_SESSION['uid'] . "");
          			// The number of movies the user has submitted.
          			$mynumovies = mysql_num_rows($mynumovies_query);
          			// Welcome the User With His/Her Username
          			echo "Welcome, $myname<br><br>";
          			// If the number of movies is one, the end of "You have Submitted NUM Movie" will be singular.
          			if($mynumovies == 1){
          				$ender = ".";
          			}
          			// If it's not equal to 1, the ending is plural.
          			else{
          				$ender = "s.";
          			}
          			// Echo out how many movies the user has submitted.
          			echo "You have submitted $mynumovies Movie$ender<br>";
          			// Echo a link to view their profile.
          			echo "<a href=\"member?uid=$uid\" title=\"View Your Profile\">View My Profile</a><br>";
          			// Echo a link to edit their profile.
          			echo "<a href=\"profile\" title=\"Edit Your Profile\">Edit My Profile</a><br>";
          			// Echo a link to submit a movie.
          			echo "<a href=\"submit\" title=\"Submit a Movie\">Submit a Movie</a><br>";
          			// Echo a link to edit their submissions.
          			echo "<a href=\"submissions\" title=\"Edit, Delete, or View your Movie uploads\">My Submissions</a><br><br>";
          			// Echo a link to logout.
          			echo "Or <a href=\"logout\" onclick=\"return log_out();\" title=\"Logout Of AVP Showcase\">Logout</a>";	
          		}
          }
          // If they aren't logged in and for some reason weren't re-directed, tell them they need to log in.
          else{
          	echo "You Are Not Logged In, Please <a href=\"login\" title=\"Log In To AVP Showcase\">Log In.</a>";
          }
          ?></center></td></tr></table></td>
          	<tr>
          		<td class="small_bottom"></td>
          	</tr>
          </table>
          <!-- END small TABLE asset -->

            I don't see anywhere that $SESSION['uid'] gets set to anything (on an earlier page, perhaps?). I do see one line

            echo "<a href=\"member?uid=$uid\" title=\"View Your Profile\">View My Profile</a><br>"; 

            That would on the next page create $_GET['uid'], but I don't see where $uid is getting set either.

              It gets set on the login page. At the top of that script, there's an if statement that sees if the uid is set, and if it isn't, you get redirected to the login. I started another topic with help with the login, and this is my final script:

              <?php
              ob_start(); 
              include("scripts/config.php");
              session_start();
              ?>
              <title><?php if(isset($_SESSION['uid'])){echo "You Are Logged In";}else{ echo "Log In To The Association of Video Professionals Showcase";} ?></title>
              <head>
              <link rel="shortcut icon" href="favicon.ico"/>
              <script type="text/javascript" src="scripts/scripts?sid=1"></script>
              <?php
              if($_SESSION["browser"] == "checked"){
              }
              else{
              	$_SESSION["browser"] = "checked";
              	echo "<script type=\"text/javascript\">
              if(navigator.userAgent.indexOf('Firefox')!=-1){
              }
              else{
              	if(confirm('You are using a internet browser other than Firefox. It is recomended that you use Firefox to view this website, for some elements may show up incorrect or not function at all. Click Ok to get the newest version of Firefox, or click cancel to hide this prompt.')== true){
              		changehref('http://www.mozilla.com/en-US/firefox/');
              	}
              }
              </script>
              ";
              }
              ?>
              <link rel="stylesheet" href="scripts/scripts?sid=2" type="text/css"/>
              </head>
              <body id="html">
              <center><a href="http://avpshowcase.com/" title="Association of Video Professionals Showcase"><img src="images/header.png" alt="" border="0"/></a></center>
              <!-- START big TABLE asset -->
              <table cellpadding="0" cellspacing="0" border="0" align="center">
              	<tr>
              		<td class="full_top"><center><br><?php if(isset($_SESSION['uid'])){echo "You Are Logged In";}else{ echo "Log In To AVP Showcase";} ?></center></td>
              	</tr>
              		<td class="full_middle"><table align="center" border="0" cellpadding="0" cellspacing="0" width="745" height="100%"><tr><td>
              <?php
              // If your uid has already been set, tell the user that.
              if(isset($_SESSION['uid'])){
              	echo "<center>You are already logged in. If you logged in as the incorrect user, please <a href=\"logout\" title=\"Logout Of AVP Showcase\" onclick=\"return log_out();\">logout</a> first and then log back in as the correct user.<br><br>If you are having log in problems, please email your issue to <a href=\"mailto:login@avpshowcase.com\" title=\"Email login@avpshowcase.com for problems that you are having with logging in.\">login@avpshowcase.com</a></center>";
              }
              // If your uid hasn't been set, proccess or show the form.
              else{
              // Variable for self submitting form.
              	$self = $_SERVER['PHP_SELF'];
              // Javasript validation for form.
              	$checksc = '<script language="javascript">
              function validate(){
              	var Check = 0;
              	if(document.form.username.value == \'\'){
              		alert(\'Please enter a valid username.\');
              		return false; Check = 1
              	}
              	if(document.form.password.value == \'\'){
              		alert(\'Please enter a valid password.\');
              		return false; Check = 1
              	}
                  if(Check == 0){
              		document.form.send.disabled = true;
              		return true;
              	}
              }
              </script>';
              // Form html tags.
              	$formt = '<form action="' . $self . '" method="post" onsubmit="return validate();" name="form">
              	<table border="0" cellpadding="0" cellspacing="0" align="center"><tr><td>Username:<br><input type="text" name="username" title="Enter your username here." value="' . $_POST['username'] . '"/><br>
              	Password:<br><input type="password" name="password" title="Enter your password here." value="' . $_POST['password'] . '"/><br><label title="Show your password as text."><input type="checkbox" name="showhide" onclick="if(document.form.showhide.checked) document.form.password.type=\'text\';else document.form.password.type=\'password\';"/>Show Password</label></td></tr></table>
              	<div align="center"><input type="hidden" value="1" name="send"/>
              	<input type="submit" value="Submit" title="Log In" name="send"/><br><br>
              </form>If you do not have a account, please <a href="register" title="Register as a Member">register</a>.<br>If you are having trouble registering, please email <a href="mailto:register@avpshowcase.com" title="Email register@avpshowcase.com for problems that you are having with registering.">register@avpshowcase.com</a> for help.<br>If you are having trouble logging in, please email <a href="mailto:login@avpshowcase.com" title="Email login@avpshowcase.com for problems that you are having with logging in.">login@avpshowcase.com</a> for help.</div>';
              // If the form has been submitted.
              	if(isset($_POST['send'])){
              		$username = (isset($_POST['username']) ? $_POST['username'] : '');
              		$password = (isset($_POST['password']) ? $_POST['password'] : '');
              		// If both username and password aren't empty, attempt login.
              		if(!empty($username) && !empty($password)){
              			$username = mysql_real_escape_string($username);
              			$password = mysql_real_escape_string($password); 
              			$query=@mysql_query("SELECT uid FROM members WHERE username=\"$username\" AND password=\"$password\"") or die(mysql_error());
              			$num = mysql_num_rows($query);
              			// If the number of rows where there is a user id that also has equal password and username as the ones submitted isn't none, loggin and redirect.
              			if($num != 0){
              				$result = mysql_fetch_assoc($query);
              				$_SESSION['uid'] = $result['uid']; 
              				// If the redirection session var from other pages isn't set, go to the index page.
              				if(!isset($_SESSION['redirect'])){
              					ob_end_clean(); 
              					header('Location: index');
              				}
              				// Else, redirect to the location that the cookie says.
              				else{
              					ob_end_clean(); 
              					header('Location: '. $_SESSION['redirect'] . '');
              				}
              			}
              			// If the number of rows is equal to 0, say you have entered inccorrect data.
              			else{
              				echo "$checksc
              				<center>You have entered a incorrect or invalid username or password. Please try again.</center>
              				$formt";
              			}
              		}
              		// If they didn't enter anything in either form field, say what they didn't enter.
              		else{
              			echo "$checksc
              			";
              			// If they didn't enter a username, say that.
              			if(empty($username)){
              				echo "<center>You did not enter a username.</center>";
              			}
              			// If they didn't enter a password, say that.
              			if(empty($password)){
                  			echo "<center>You did not enter a password.</center>";
              			}
              			echo "
              			$formt";
              		}
              	}
              	// If the form has not been submitted, print the form.
              	else{
              		echo "$checksc
              		$formt";
              	}
              }
              ?>
              </td></tr></table></td>
              	<tr>
              		<td class="full_bottom"></td>
              	</tr>
              </table>
              <!-- END big TABLE asset -->
              </body>

                SOLVED. I accidentally had the variable $uid be set in several other pieces of my code, and i didn't know that $uid counts as $_SESSION['uid']. Thank you all for helping my though.

                  One more reason why you should have register_globals turned off, and access your session variables exclusively through $_SESSION.

                  PS: bump is considered rude.

                    Write a Reply...