...

View Full Version : Session problems, havent been able to figure it out on my own



jediman
04-05-2004, 08:33 PM
Hi all, I have been having a rough time trying to get some sessions working...first off, I think this code that i use, to start a session upon having the user login and have them verified against a mysql db, SHOULD WORK


echo "logged in";
$_SESSION['name'] = $username;
session_id();
$_SESSION['login'] = 'yes';
header("Cache-control: private");


Again the user has been verified that their name and pass exists and is correct. As for the sessions, I have some issues with them. They seem to be started and such ( I have session_start(); on the page right after <?php
so it is in there, unless it needs to be elsewhere?
I have a functions.php where I was trying to do a function logincheck()
and then have the code to check to make sure that there is a session started for that particular user. what I am having problems doing is jsut that. I cant seem to get it to validate anything so of course its not working. How in the heck can I do this? I am setting up a family site, and only those who I manually approve (from the family), are able to login and then view the site. I want to secure it by forcing a login check on all of the pages (that way someone cant view anything, or post anything without being authorized. Can someone help me out? I have checked over php.net and such, and I am still I guess confused, so hopefully someone can help me out!! As long as I see an example that would work with what I got (unless im registering the sessions wrong of course lol) then I should be able to do the rest. Also, would the check need to occur in a <pre></pre> or the <head> section or would the body be fine? Also would the vars need to be global (which usually is a bad thing right?) or would this be a cookied issue, which I cant figure out myself either. Thanks for any info! I really appreciate this!!

Nightfire
04-05-2004, 08:43 PM
Try this:


<?php
session_start();
$_SESSION['name'] = $username; //Unsure where you're getting $username from, if it by url or form, use the super globals ($_GET or $_POST)
session_id(); // This isn't doing anything
$_SESSION['login'] = 'yes';
header("Cache-control: private");
echo "logged in<br>";
print_r($_SESSION); // Shows info from the session, checks if it's working or not

?>

raf
04-05-2004, 08:43 PM
What is your actual problem?

I don't think you can echo something before sending header-info i would change that. I also don't understand what the session_id() is doing inthere

It's no a cookie-issue. Sessions will work, regardless of the client cookie-settings.

<edit>Nightfire, did we synchronise watches/brains ?</edit>

Nightfire
04-05-2004, 09:03 PM
On the third beep, wasn't it?

jediman
04-05-2004, 09:38 PM
Thats cool and all, but once that is set and the user has been verified/logged in, how would i setup a function in my functions.php to CHECK to see if a login session exists, and if so then allow the user to proceed and see a page....thats the other thing I need. And if they arent logged in/verified, then I need to direct them to the login page. Get what I mean? Thanks for the help!

Nightfire
04-05-2004, 09:41 PM
To check they're logged in, use something like:


<?php
session_start();
if(isset($_SESSION['login'])){
echo 'logged in';
}else{
header("Location: loginform.php");
}
?>

jediman
04-05-2004, 09:54 PM
but wouldnt that start a NEW session? I am unable to actually redirect users with the header function in php for some weird reason...any clues as to why that wouldnt work , or am I doing something wrong... isnt it header('Location: wherever'); ?
Ive tried the variations of it that Ive found and it never seems to redirect :P

Nightfire
04-05-2004, 10:01 PM
All it's doing is seeing if the session variable loggedin exists. If it doesn't then it redirects to loginform.php. Not sure why your code isn't working, can you show your code?

jediman
04-05-2004, 10:07 PM
Here is my functions.php :


<?php

function checklogin()
{

session_start();
if(isset($_SESSION['login']))
{
echo "logged in";
}
else
{

echo "Not logged in";
}
}




function registersession($username)
{

$_SESSION['name'] = $username;
$_SESSION['login'] = 'yes';
header("Cache-control: private");
echo "logged in<br>";
print_r($_SESSION); // Shows info from the session, checks if it's working or no


}


?>


the portion of code going to registersession...coming from the login.php :


$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
if($num > 0)
{
registersession($username);

}else{
echo "Invalid Username and/or Password! Could not log you in. Please check your credentials and try again. This attempt has been logged.";
session_destroy();
}


When just using that login form, if I login correctly, it gives me the your logged in message, and the session id. However, I cant get it all to stay for some reason. I am running windows xp pro with apache 1.x if that helps, and something like php version 4.x something or other..a stable release that didnt have issues usually lol. Hope that helps. $username is actually posted from the form as


$username = $_POST['username'];
$password = $_POST['password'];

Thats where that is coming from :)


EDIT:

Note that session_start(); is also at the top of my login.php page!! its the first thing after the <?php line!

raf
04-05-2004, 10:08 PM
but wouldnt that start a NEW session? I am unable to actually redirect users with the header function in php for some weird reason...any clues as to why that wouldnt work , or am I doing something wrong... isnt it header('Location: wherever'); ?
Ive tried the variations of it that Ive found and it never seems to redirect :P
This could be because you already sent output to the client before redirecting. But we indeed can help you better if we see the code.

As for the sessioncheck, i'd use


<?php
session_start();
if(!isset($_SESSION['login'])){
header('Location: ./loginform.php');
}
?>

raf
04-05-2004, 10:21 PM
Pots crossed.

OK. First, change
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();

into


$result=mysql_query($query) or die ('Queryproblem');
$num=mysql_num_rows($result);
/*mysql_close(); --> no need to close, or else first free the resultset. Like
mysql_free_result($result);
mysql_close(); */


Then, about the logincheck --> i would not include the functionfile. I would include a headerfile (that does some checking, logging or whatever, and include the check there. Not inside a funcion (See previous post for code). Also, don't output inside a function --> store the output' in a variable and return that when the function is completed.

Can you make this

However, I cant get it all to stay for some reason. a bit more concrete

jediman
04-05-2004, 10:30 PM
I'm afraid im still lost...

jediman
04-06-2004, 01:20 AM
Ah ok, to eliviate. Once ive logged in, the session has started. Thats fine, great, dandy. However, since for whatever reason only God probably knows, header redirection is not working, so i just delete some things and just go back to my index.php . Then thats where that login check is supposed to occur, but doesnt seem to be picking up the fact that a session has indeed already started. So what that is telling me is things arent passing between the two.. I really should just probably pass out the session id to the pages, and have it check that way, and also have it quickly check against like i dunno, the database, and have it insert the current session into that? would that be suffice? or would that just add a whole lot of uncessesary overhead to it all?

jediman
04-06-2004, 02:35 AM
<html>
<head>
</head>
<body>
<?php
session_start();

require("system/config.php");
require("system/functions.php");

echo"<title>$title -Please Login</title>";


if($_POST['login'])
{
$status = "active";
//post the fields
$username = $_POST['username'];
$password = $_POST['password'];
$username = md5($username);
$password = md5($password);
//connect to the db
mysql_connect($connection,$user,$pwd);
@mysql_select_db($database) or die( "Unable to select database");
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password' AND status = '$status'";
$result=mysql_query($query);
$num=mysql_numrows($result);
$id=mysql_result($result, "id");

mysql_close();
if($num > 0)
{

$_SESSION['name'] = $username;
$_SESSION['login'] = 'yes';
$sid = session_id();
mysql_connect($connection,$user,$pwd);
@mysql_select_db($database) or die( "Unable to select database");
$secondquery = "UPDATE users SET sid = '$sid' WHERE id = '$id'";
$rs=mysql_query($secondquery);
mysql_close();
if(!$rs)
{
echo "Error Updating User session id!".mysql_error();
}else{


header("Cache-control: private");
echo "logged in<br>";
//print_r($_SESSION); // Shows info from the session, checks if it's working or no
echo "<a href=index.php>Back To Main Page</a>";
}

}else{
echo "Invalid Username and/or Password! Could not log you in. Please check your credentials and try again. This attempt has been logged.";

session_destroy();
}
}
else
{
?>
<form action="login.php" method="post">
<table border=1>
<tr>
<td nowrap><b>Username:</b></td><td><input type="text" name="username" size="32"></td>
</tr>
<tr>
<td nowrap><b>Password:</b></td><td><input type="password" name="password" size="32"></td>
</tr>
<tr>
<td><input type="submit" name="login" value="Login"></td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>


Here is my login script. I now have a field in the users table where the sid gets set when the user logs in. Now, can someone please write me a function that I can use/include on all pages, to be sure that the user is logged in, and if so allow the page to be viewed? Ive tried a bunch of times, but nothing seems to really work, and I am at a total loss! PLEASE HELP! THANKS!!!!!

raf
04-06-2004, 08:50 AM
If you want more help, then you need to give us more info. 'Doesn't seem to work' etc is useless.
I also see you are not following my other advice on the depreciated mysql_numrows and the connectionclose, so i'm not really motivated to point out things you should set straight in the last code you posted.

The code nightfire and I posted should work just fine, and you better try getting it running then changing direction. Just print out the sessionvariales (with print_r($_SESSION); ) right after you set them, before you redirect and on top of all pages you use. And then look where it gets dropped and go backwards or print the code inbetween the last succesfull print and this one.

jediman
04-06-2004, 02:08 PM
If you want more help, then you need to give us more info. 'Doesn't seem to work' etc is useless.
I also see you are not following my other advice on the depreciated mysql_numrows and the connectionclose, so i'm not really motivated to point out things you should set straight in the last code you posted.

The code nightfire and I posted should work just fine, and you better try getting it running then changing direction. Just print out the sessionvariales (with print_r($_SESSION); ) right after you set them, before you redirect and on top of all pages you use. And then look where it gets dropped and go backwards or print the code inbetween the last succesfull print and this one.
I cant even redirect. The header function doesnt work! When I try to carry sessions around, they dont! I cant login on login.php, clear the address from the address bar in the browser, retype the address to go back to the same site, and just access index, have it check to see if a session already exists for the user, and if not force them to login, and then allow them to view the page. Thats what I need, thats what doesnt happen. I dont know if its the php version I am using, and before I go and change it I want to know if its a windows xp/apache 1x issue first. I have no idea otherwise on sessions, and I cannot find anything on the web that suites the methods on how I need to figure out how to do these. I cant learn from two word examples like ive seen all around, and i am totally lost. I hate using the phpBB wrapper because I dont want to fuddle with it. I appreciate the help !

Nightfire
04-06-2004, 03:16 PM
You have html and text printed to the page before you create a session or header. You can't have ANYTHING outputted to the browser before them. You should've gotten loads of errors mentioning that.

raf
04-06-2004, 03:42 PM
You have html and text printed to the page before you create a session or header. You can't have ANYTHING outputted to the browser before them. You should've gotten loads of errors mentioning that.
Indeed.

Which is now said for the 4 time :
2 times my meself, 2 times Nightfire.

--> Trust us : Change it.


I cant learn from two word examples like ive seen all around, and i am totally lost.
You hardly need 2 words to code this ;)
If you'r ost, then strip it down (copy your file and remove all code that isn't strictly necessary) and get the session and redirect working first. Then start adding your code again.

I've got the impression you're working on some outdated 3 party code, so i'd recommend you follow my advice and get rid of depreciated and unnescessary code.
Agter you have it running, we can look at further optimalisations.

jediman
04-06-2004, 05:43 PM
I am going to try that now on my laptop here if it decides to work still :-/ hasnt been the same since i got my car totaled the other day :(

I am hoping that it keeps me logged in lol. I am getting the latest apache release as well as the latet stable release of php, and I am going to just test if keeping a session works on its own. I will let you know later.

Also, lemme ask you this...what is the way you guys would have a user login? Would you bother to have session id field in the mysql db if you were using one, to match it up? or...? Also, if not, then would you rely on sessions or cookies?

-Jediman

jediman
04-06-2004, 06:04 PM
Yeah that seems to be the problem! Thanks guys! HEader redirects also working! I will play around with this more tonight:)

raf
04-06-2004, 08:39 PM
Also, lemme ask you this...what is the way you guys would have a user login? Would you bother to have session id field in the mysql db if you were using one, to match it up? or...? Also, if not, then would you rely on sessions or cookies?
Yes. I use a db with a sessiontable that contains the PHP sessionID, the IP (if it stays the same during the first x pages) and a flag if the client accepts persistent cookies.
Sessionmanagement and an applications security don't have the same goals, so relying on sessions to check if a user is logged in, has some disadvantages and is in my opinion not the way to go if you wan't to write a large, ecure but still userfriendly application.
If you have a user with a persistent cokie (and preferable a stable IP --> so no AOL users that get a different IP with each pagerequest) then you can even automatically regenerate a timed out PHP session and plenty more other usefull stuff.
I also believe it to be more secure then only relying on session-variables.

jediman
04-07-2004, 12:14 AM
Cool. I figured i'd be pretty secure since right now I have it check for username, password, AND if you account is active, because i only approve accounts from family members, and they tell me when they are signing up. That way I have some secured control over the database which is nice. As for the ip table, I think that would be a cool way to go. Would the ip table be permanent, ie; always contain the usernames and passwords, and only the ip tables would essentially be dynamic for that field? Or have it automatically inject the table with updated info on whos doing what when and where?

raf
04-07-2004, 12:31 AM
Would the ip table be permanent, ie; always contain the usernames and passwords, and only the ip tables would essentially be dynamic for that field? Or have it automatically inject the table with updated info on whos doing what when and where?
Hmm. Not sure i get this.
Say you have your usertable like

userID | userpwd | username |fixedIP

In your loginscript, you check the username and pwd and if correct, you then insert a new record inside the sessiontable, that could look like

sesID | userID | IP | PHPsesID | UseCookie

The userID, you get from your logincheck, the PHPsesID is the session_id(), the IP iyou can get with


if (isset ($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$UserIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else {
$UserIP = $_SERVER['REMOTE_ADDR'];
}

and if he accepts the persistent cookie, you can check by setting one and then trying to read it.

If your familymembers would have fixed IP's (--> so each time they connect to the web, they get the same IP), then you can store that IP inside the usertable and check on both the pwd and IP for that user.
An alternative would be to set a cookie on their machine, with an encoded value, and store the original value + the userspecific decoding key inside the userable.

jediman
04-07-2004, 04:00 PM
Ah coolness. Yeah I know INTERNALLY on the lan theyd have the same IP but if accessing the site from work or somewhere else remote, that might not be the best solution. Also if they are on a public computer. Hmmm. Cookies arent always usefull because alot of people may block them and then delete them when one comes their way. Its kinda spywareish anyhow, so I'd rather not do the cookie route. I think the session table would be best. I can just create a seperate session and then have it lookup the stuff and return the values. Right now once you close your browser, you have to login again because your session is no longer there essentially, but otherwise its ok. Thanks for the tip. I will have to look into it more tonight. Right now I am setting the site up mainly to post family news, publish an "address book", etc, and I just wanted it as secure as possible. Since the usernames and passwords all are md5's, I figured it be secured enough right :) And I dont think you can quite fake a session for php can you? I mean its not like you can just set the address with ?whatever_session=234432023482048
I mean that just wouldnt quite work, and trying to figure out the whole session id would be such a chore.

raf
04-07-2004, 04:43 PM
Well, if your users don't accept cookies, then session hijacking certainly isn't impossible.
In such cases, you'd best take a look at session_regenerate_id() ( http://www.php.net/manual/en/function.session-regenerate-id.php ) to generate a new sessionID for each request. This way, session-hijacking by sniffing the SID or getting it inside an external site, becomes very unlikely (unless the user falls asleep).

Accepting persistent and session cookies has got nothing to do with spyware. Accepting cookies makes your application safer, and also or the user. So i always recommend users to accept cookies. If they don't have a stable IP (an IP that stays the same during the session) then i make it required.

jediman
04-07-2004, 04:53 PM
Ok then, sounds like a good plan. How would I also issue a cookie then and check for that...on top of the session checking i already have.

Nightfire
04-07-2004, 04:59 PM
rtm http://www.php.net/setcookie

jediman
04-07-2004, 08:21 PM
Meh, now Im kinda confused. Sounds like an IP table would be good, but essentially a cookie too??? Hmmmz. I could setup the ip table, but its still a bit of a security risk isnt it? I mean if its the same ip addy, then what. I mean if they forgot to logout or something, or perhaps I could have a timeout function of sorts, like if they logged in like at 1:30pm, and then they all of a sudden come back to the site via the history at like 10pm, then it could say forget it! I dunno. Then again the cookies could be a better route but some people tend to block them regardless. Hmmmm....right now my site forces you to login, be authorized and only authorize if your account has the enabled flag regardless. I suppose people could sniff around, but then again php shouldnt be letting that out quite like that. I will toy with the ip tables I suppose and have it do it that way?

jediman
04-07-2004, 08:35 PM
I read up on the cookies and session_regenerate, but I still am not sure on how to do the setup now. When the user logs in, just set the cooker, like setcookie('user', $username, time()+3600*-5, '/', 'www.example.com');
and leave it as is?

Or forget that and just do an ip table..but then when the session is checked, if no session is checked then have it look for the ip addy, etc???



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum