Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Session variable sometimes not transferring

Status
Not open for further replies.

flnMichael

Programmer
Nov 13, 2003
96
US
Hey,
I have a couple pages that require a session variable throughout each page. After I log in at the login page and enter the right username and password, the session is set to 1 for Admin and 2 for others.

Code:
If objRS("Password") = Request.form("Password") Then
  if Request.form("Username") <> "Admin" then
    session("Admin") = "2"
  else
    session("Admin") = "1"
  end if
end if

session("error") = "0"
Response.Redirect("AdminPage.asp")

I have followed the path of the logon page and have found that before it leaves to redirect to another page, the session is set correctly. On the top of my next page, I have this snippet of code:

Code:
dim rights
rights = session.Value("Admin")
if rights <> "1" then
  if rights <> "2" then
    Response.Redirect("Login.asp")
  end if
end if

This will always redirect. When I play around with the code, I find that the session variable isn't always the same (either a "0" or "2" shows up as the value, and this is random), even though it is always correct when I response.write it on the login page ("1"). I have changed my browser settings to check for a newer version of the page every visit, but no different. Can anyone tell me what may be going on?

Thanks
Mike
 
Where you set session("Admin") to "0"? Obviously somewhere else...

------
"There's a man... He's bald and wears a short-sleeved shirt, and somehow he's very important to me. I think his name is Homer."
(Jack O'Neill, Stargate)
[banghead]
 
At the top of the Login Page I have the session variable being set to 0

Code:
session.Value("Admin") = 0

so every time I get to the Login page, it resets the session.
 
On one page you use:
[tt] session("Admin")[/tt]
And on another you use:
[tt] session.Value("Admin")[/tt]
That doesn't look right.

Tracy Dryden

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
still doesn't make a difference. I tried it with the session.value() and the session(). It was working a couple months ago, I just don't see what can be going wrong!!!
 
The very first page, the Login.asp page. In all my subsequent pages, I check what the session variable is and go from there (see first post)
 
on the subsequent pages, did you check the value of rights, session("Admin") and session.Value("Admin")?

session.Value() usually is used to reference a form. ex-

<form>
<input type=text name=fullname>
</form>
...
...
...
somevar = session.Value("fullname")
 
Here's what I do, in order

Login page, on top
Code:
session.Value("Admin") = 0

Once I log in correctly, depending on if I want to be admin or operator
Code:
session.value("Admin") = "1" or session.value("Admin") = "2"

on subsequent pages after
Code:
dim rights
rights = session.Value("Admin")
if rights <> "1" then
  if rights <> "2" then
    Response.Redirect("Login.asp")
  end if
end if

Would I say rights.value instead?
 
I print out the values for all three and they are the same each time.
 
no. what are the values, all zeros? also, try getting rid of the .value's that you have. session("admin") will work just fine.
 
It depends on what it wants to print out at the time. I can get all 0's or all 1's, but they are all the same when I get them. I'll try the session() instead of session.value()
 
Ok, it still doesn't work.

Now I have another question. The page following the login, upon correct login, is the adminpage.asp. I made the changes to the page to not redirect and just print out the values of the session. What I see when I continuously refresh is at the top I get the printed values of all three response.writes (rights, session(), and session.value()). Now sometimes they appear and sometimes they don't. Might this have anything to do with my problem?
 
can you post all of your code. it's kind of hard to see what's going on with just peices.
 
yeah, I know what you mean. I'll get the 2-3 pages up, but is there a way to attach, they are fairly large (256 lines or more)? Or maybe I can email them to you?

 
Here's the Login.asp page:

Code:
<!-- #INCLUDE file="adovbs.inc" -->
<%

session("Admin") = 0

%>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Microsoft Word 97">
<title>Paveway Torque Page Login</title>


</head>


<script language="JavaScript"><!--


function rollon(imgName) {
        if (document.images) {
        imgOn = eval(imgName + "on.src");
        document[img]ame[/img].src = imgOn;
        }
}
function rolloff(imgName) {
        if (document.images) {
        document[img]ame[/img].src = eval(imgName + "off.src");
        }
}


/* This code is Copyright (c) 1996-1998 internet.com LLC. All rights
* reserved. To receive the right to license this code for use on your site
* the original code must be copied from webreference.com. License is
* granted to user to reuse this code on their own web site if and only if
* this entire copyright notice is included. Code written by Andy King of
* webreference.com. */

// 3-11-97 one menu only code extracted
// 12-22-98 added sized select menu for a scrolling select list
// 12-23-98 bug fix, added check for selected option (-1 = no sel)
// 1-1-98 bug fix for ns 2.02 (doesn't supt names), added getFormNum

function getFormNum (formName) {
	formNum =-1;
	for (i=0;i<document.forms.length;i++){
		tempForm =  document.forms[i];
		if (formName == tempForm) {
			formNum = i;
			correctForm = tempForm;
			break;
		}
	}
	return formNum;
}

function jmp(formName,elementNum) {
	getFormNum(formName);
	if (formNum>=0) {
		with (document.forms[formNum].elements[elementNum]) {
			i=selectedIndex;
			if (i>=0) location=options[i].value;
		}
	}
}
// -->
		</script>


		<SCRIPT language="JavaScript"><!--
/* Menu system script 1 of 3 Identifies browser ability to support menus DO NOT CHANGE */
	NS4 = (document.layers);
    IE4 = (document.all);
    ver4 = (NS4 || IE4);
   	isMac = (navigator.appVersion.indexOf("Mac") != -1);
  	isMenu = (NS4 || (IE4 && !isMac));
  	function popUp(){return};
	function popDown(){return};
	function startIt(){return}
	if (!ver4) event=null;
// -->
		</SCRIPT>
		<SCRIPT language="JavaScript1.2"><!--
/* Menu system script 2 of 3 Establishes menu style DO NOT CHANGE */
	if (isMenu) {
	menuVersion = 3;
	menuWidth = 160;
	childOverlap = 5;
	childOffset = 2;
	perCentOver = null;
	secondsVisible = .5;
	fntCol = "#333333";
	fntSiz = "9";
	fntBold = false;
	fntItal = false;
	fntFam = "arial,helvetica,espy,sans-serif";
	backCol = "#f9f9f9";
	overCol = "#ffffcc";
	overFnt = "#ff3300";
	borWid = 1;
	borCol = "#333333";
	borSty = "solid";
	itemPad = 3;
	imgSrc = "images/tri.gif";
	imgSiz = 9;
	separator = 1;
	separatorCol = "gray";
	isFrames = false;
	keepHilite = true;
	NSfontOver = true;
	clickStart = false;
	clickKill = false;
	showVisited = "gray";
}
// -->
		</SCRIPT>
			<SCRIPT language="JavaScript1.2"><!--
/* Menu system script 3 of 3 Determines the left edge of the display area and assigns the value to the variable leftEdge then calls the menu content file hierArrays and the menu object definition file hiermenus DO NOT CHANGE */
    if (isMenu) {
    	}
// -->
			</SCRIPT>

</head>

<body bgcolor="white" link="#003366" alink="#ff3300" vlink="#666666" marginwidth="2" marginheight="0" leftmargin="2" topmargin="0">
  <center>
    <FONT face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular"><A name="pagetop"></A><!-- Header Table Begins -->
      <TABLE border="0" cellpadding="0" cellspacing="0" width="760">
	    <TR>
	      <TD align="left" valign="top" width="138"><A href="[URL unfurl="true"]http://home.ray.com"><IMG[/URL] src="images2/logo_i.gif" border="0" alt="Raytheon" width="138" height="48"></A></TD>
	      <TD colspan="2"><IMG src="images2/siteid_i.gif" border="0" usemap="#utilities" width="622" height="48"><MAP name="utilities"><AREA href="[URL unfurl="true"]http://home.ray.com/"[/URL] coords="2,32,72,46" shape="rect"><AREA href="[URL unfurl="true"]http://home.ray.com/using/"[/URL] coords="191,32,257,46" shape="rect"><AREA href="[URL unfurl="true"]http://home.ray.com/search.html"[/URL] coords="147,32,180,46" shape="rect"><AREA href="[URL unfurl="true"]http://home.ray.com/phones/welcome.html"[/URL] coords="84,32,135,46" shape="rect"></MAP></TD>
	    </TR>
	    <TR>
	      <TD colspan="3" align="left" valign="top" nowrap><A href="[URL unfurl="true"]http://home.rms.ray.com/test_equip/"[/URL] onmouseover="popUp('elMenu1',event)" onmouseout="popDown('elMenu1')"><IMG src="images2/nt_tab1_d.gif" border="0" name="tab1" width="138" height="20"></A><A href="[URL unfurl="true"]http://tenwww.tuc.us.ray.com"[/URL] onmouseover="popUp('elMenu2',event)" onmouseout="popDown('elMenu2')"><IMG border="0" name="tab2" src="images2/nt_tab2_n.gif" width="136" height="20"></A><A href="[URL unfurl="true"]http://tenwww.tuc.us.ray.com"[/URL] onmouseover="popUp('elMenu3',event)" onmouseout="popDown('elMenu3')"><IMG border="0" name="tab3" src="images2/nt_tab3_n.gif" width="153" height="20"></A><A href="[URL unfurl="true"]http://tenwww.tuc.us.ray.com"[/URL] onmouseover="popUp('elMenu4',event)" onmouseout="popDown('elMenu4')"><IMG border="0" name="tab4" src="images2/nt_tab4_n.gif" width="166" height="20"></A><A href="contacts.htm"><IMG border="0" name="tab5" src="images2/nt_tab5_n.gif" width="167" height="20"></A></TD>
        </TR>
	  </TABLE>
      <!-- Header Table Ends -->
      <!-- Body Table Begins -->
	  <TABLE border="0" cellpadding="0" cellspacing="0" width="760">
	    <TR>
	      <TD colspan="3" align="left" valign="top" nowrap><IMG height="2" width="760" src="images2/tabshadow.gif" border="0"></TD>
	    </TR>
	    <TR>
	      <TD width="138" nowrap valign="top" align="left"><!-- Pod Nav Begins -->
	      </TD>
	      <TD valign="top" width="391">
	      </TD>
	    </TR>
	  </TABLE>
	  <!-- Body Table Ends -->
    </FONT>
    <!-- Body Table Begins -->
<div align=center>
  <a name="pagetop"></a>
    <form method='POST' action='UserConfirm.asp' id=form1 name=form1>
      <table width=760 align=center border=0>
        <tr>
          <td colspan="3">&nbsp;</td>
        </tr>
        <tr>
          <td><center>
            <%
               if session("error") = "1" then
            %>
              <font color=red size=4><b>Login falied. Please try again<b>
            <%
               end if
            %>
              <table cellpadding=5 cellspacing=0 border=1 width=120>
                <tr>
                  <td valign=top width=138 bgcolor='0000FF'>
                    <center><font color=yellow size=2><span class=GBAN><b>All Users log in here</b></span></center>
                  </td>
		        </tr>
                <tr>
                  <td align=center valign=top class='menubar12' bgcolor='#dddddd'>
                    <font size=2>Username:<br><input type='text' name='Username' size=8>
                    <br>Password:<br></font><input type='Password' name='Password' size=8>
                    <input type='button' name='login' alt='Login' value='Login' onclick='checkvalues(this.form);'>
                  </td>
                </tr>
              </table>
          </td>
        </tr>
      </table>
    </form>
<script language="JavaScript">
<!--
function checkvalues(form)
{
  if (form.Username.value == "")
   {
     alert("Please Enter in a Username");
     form.Username.focus();
     return false;
   }

  else if (form.Password.value == "")
   {
     alert("Please Enter in a Password");
     form.Password.focus();
     return false;
   }

  else
    form.submit();
}
//-->
</script>


</body>

</html>

I guess all that is needed there is the top..

Here's the userconfirm.asp page, where I check against the database:

Code:
<% Option Explicit 'forces variables to be defined prior to use%>
<% Response.Buffer = True 'waits till page is processed before sending response%>
<!--#include file="PavewayConfig.asp"-->
<%

Dim SQLQuery
Dim objConnection, objRS
dim temp

'Check If Admin Login

If Request.form("Username") = strAdminName Then subAdminCheck

'Open and search recordset

'Set "objConnection" to database connection object.
Set objConnection = Server.CreateObject("ADODB.Connection")

'dbconn = "DRIVER={Microsoft Access Driver (*.mdb)};" _
'          & "DBQ=" & Server.MapPath("./paveway_torque.mdb") & ";"
dbconn = "dsn=Torque;uid=webqueries;pwd="

'Open database
objConnection.Open dbconn

'Define SQL variable
SQLQuery = "SELECT Password FROM users WHERE Username='" & Request.form("Username") & "'"
Response.Write(SQLQuery)
'Set Recordset
Set objRS = objConnection.Execute(SQLQuery)

'set temp = objRS("Password")
'Response.Write(temp)

'Check form input results against recordset

'If recordset contains no records, user does not exist.
If objRS.EOF Then

	'Logging subroutine
	If intLog = 1 Then subLogWrite 0

  session("error") = "1"
  Response.Redirect("Login.asp")

'Check if password is correct
ElseIf objRS("Password") = Request.form("Password") Then

	'Logging subroutine
	If intLog = 1 Then subLogWrite 1

	'Cookie subroutine
	'subWriteCookie

	'Custom Code subroutine
	subCustomCode

Else

	'Logging subroutine
	If intLog = 1 Then subLogWrite 0

  session("error") = "1"
  Response.Redirect("Login.asp")

End If

objRs.Close
Set objRs = Nothing
objConnection.Close
Set objConnection = Nothing


' SUBROUTINES

'Admin Login Check

Sub subAdminCheck

	If Request.form("Password") = strAdminPass Then

		'Logging subroutine
		If intLog = 1 Then subLogWrite 1

		'Declare admin session variable:
				session("Admin") = "1"
				rights=session("Admin")
				Response.Write("Session variable is:")
				Response.Write(rights)
        Response.Write(".")

		'Redirect admin to admin script:
		Response.Redirect("AdminPage.asp")

	Else

		'Logging subroutine
		If intLog = 1 Then subLogWrite 0

		Response.Write "Incorrect password."
		Response.End

	End If

End Sub



'Cookie subroutine

Sub subWriteCookie

	If Request.Form("SaveCookie") = 1 Then

		Response.Cookies("Preferences")("Username") = Request.form("Username")
		Response.Cookies("Preferences")("Password") = Request.form("Password")
		Response.Cookies("Preferences").Expires = "January 1, 2005"
		Response.Write("Cookie saved.<p>")

	Else

		Response.Cookies("Preferences")("Username") = ""
		Response.Cookies("Preferences")("Password") = ""

	End If

End Sub


'Logging Subroutine

Sub subLogWrite(intResult)

	'Dim objFileSys, objLogFile
	'Set objFileSys = CreateObject("Scripting.FileSystemObject")
	'Set object to OpenTextFile. Location, (8) = append, (true) = create file if does not exist.
	'Set objLogFile = objFileSys.OpenTextFile(strLogURL, 8, True)

	'Write to file then close.
	'objLogFIle.Write(intResult & " | ") 'request result of login attempt
	'objLogFile.Write(Request.form("Username") & " | ") 'request name
	'objLogFile.Write Request.ServerVariables("REMOTE_HOST") 'request IP info
	'objLogFile.Write(" | " & Date() & " | " & Time() & " | ") ' date and time
	'objLogFile.WriteLine Request.ServerVariables("HTTP_USER_AGENT") 'request browser info
	'objLogFile.WriteBlankLines(1)
	'objLogFile.Close

End Sub
%>


And the sub function that sets the session
Code:
<%
'ASP Client Check - Configuration File

Dim dbconn, intLog, strLogURL, strAdminName, strAdminPass, rights

dbconn = "dsn=Torque;uid=webqueries;pwd="

'Set intLog to "1" if you want to keep a log of attempts to enter.
intLog = 1

strAdminName = ""
strAdminPass = ""

Sub subCustomCode
  temp = lcase(Request.form("Username"))

  if temp <> "admin" then
    session("Admin") = "2"
  else
    session("Admin") = "1"
  end if

  session("error") = "0"
  Response.Redirect("AdminPage.asp")
End Sub
%>
 
Check that your server doesnt run web gardens or some kind of server load shareing

I had a simiar problem and if the server switches gardens or if the load share thing kicks in it will forget your session variable!

You need the domain in application isolation

}...the bane of my life!
 
in the userconfirm.asp page, how will the following code ever evaluate to true?

'Check If Admin Login

If Request.form("Username") = strAdminName Then subAdminCheck

is there code to set strAdminName in the PavewayConfig.asp page that's included?
 
guitardave78
When you say web gardens I guess in my terms you mean web farm, right? If that's the case then that may be the issue. We are running this on a cluster server. I'll check on that.

briancostea
I believe that part of the code was placed in there as a possible function to run, but never made the cut. I just never got around to deleting it. I initially set strAdminName to be "" in the PavewayConfig.asp page.
 
guitardave78
I realized that web farm and web garden are two seperate things, and to answer the question we are running both. Each individual server has multiple processors and both servers are running the same application. I'm still seeing if I need to set something up on the server that I missed somewhere.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top