Solved

URGENT: PHP sessions question

Posted on 2003-11-02
21
314 Views
Last Modified: 2006-11-17
I'm switching over to sessions from cookies.

My current login form is:

<form name=login action=$PHP_SELF method=post>
      <B><CENTER><B>
      
        <font color="white" size="1" face="Verdana, Arial, Helvetica, sans-serif"> <b>Username: <br>
          <input name="username" type="text" size="10"><br>
          </b> <font color="white" size="1" face="Verdana, Arial, Helvetica, sans-serif"> <b>Password: <br>
            <input name="password" type="password" size="10">
            </b>
            <input type="hidden" name="userAction" value="Log In">
          <input name="image" type="image" src="/images/login.gif" align="middle"></font>
              </form>

And at the top of my page I have included the following:

<?
session_start();
mysql_connect ('localhost', 'Edited by request');
mysql_select_db ('Edited by request');
header("Cache-control: private");
$username = $_POST['username'];
$password = $_POST['password'];
$sql = mysql_query("SELECT * FROM table WHERE username='$username' and password=encrypt('$password','$username')");");
$login_check = mysql_num_rows($sql);
if($login_check > 0)
{
// Get the user's input from the form
echo "in login check";
// Register session key with the value
   session_register('username');
   $_SESSION['username'] = $username;
}
?>

I want the $username variable to contain the username so I can use it throughout my other code.

I'm new to sessions so I have no idea. I want to use sessions with cookies if the user has cookies enabled and checks a "Remember me" box. This question is worth 1000 points actually, to whomever can answer it. I will make another question and give the other 500 points that way.

Thanks in advance!
0
Comment
Question by:drakkarnoir
  • 9
  • 7
  • 3
  • +2
21 Comments
 

Expert Comment

by:rnetox
Comment Utility
I wont fiz your script.. i don´t like to do this but you can see:

www.phpfreaks.com <- tutorial section
www.phpbuilder.com <- articles section

so read and study..
0
 

Author Comment

by:drakkarnoir
Comment Utility
I've read both those, and it hasn't worked for me which is why this question is worth 1000 points to begin with...
0
 

Author Comment

by:drakkarnoir
Comment Utility
Oh and global_registers are ON
0
 
LVL 17

Expert Comment

by:smozgur
Comment Utility
Actually you don't need

  $_SESSION['username'] = $username;

code line, because

   session_register('username');

already set $_SESSION['username']  as $username (which has been assigned above)

have you tried using

session_start();
session_register('username');

and then, after logout

session_destroy();

?

Suat

0
 
LVL 8

Expert Comment

by:inq123
Comment Utility
Hi drakkarnoir,

I don't understand this sentence of yours: "I want the $username variable to contain the username so I can use it throughout my other code."  Isn't the $username already have it from the $_POST['username'].  If I understand you correctly, what you really should do is:

# other codes do not need to be changed
if($login_check > 0)
{
   $_SESSION['username'] = $username;
}
?>

Then in your other scripts, whenever you need to use username for the same session, just put in your script <? session_start(); $username = $_SESSION['username']; # other codes can ensue ...

Then the username is back into $username from the stored session variable.  Basically in your code, you shouldn't mix session_register and $_SESSION['username'] = ...

As for the cookie issue, it's used by php by default for session.  A few useful settings in your php.ini that controls cookie usage include: session.cookie_secure (default no), session.use_cookies (default on), session.use_only_cookies (default off).

If you need to have per-script setting on some php.ini variables such as session.use_cookies, then you can use the ini_set() function to set for that script.

So I think that pretty much covers your questions.

Cheers!
0
 

Author Comment

by:drakkarnoir
Comment Utility
I tried that, and it wouldn't still pickup my username after I clicked on another link on my site, with the session_start(); at the top.
0
 
LVL 4

Expert Comment

by:duerra
Comment Utility
Greetings,
Firstly, you shouldn't use this line:
session_register('username');

You should do it as you have done right below:
$_SESSION['username'] = $username;

If your php.ini has register_globals set to OFF, this may be why your script is causing you problems.  If register_globals is off, session_register *will not work!*

Also, every single page that you want to use $username on *needs* to have session_start() called on it.  If session_start() is not called, you will not import your $_SESSION superglobal array.  

Let me know what happens.
0
 
LVL 8

Expert Comment

by:inq123
Comment Utility
duerra, you haven't been reading OP's posts or others' posts carefully :-).  OP said register_globals are ON, also I already suggested don't mix session_register and $_SESSION and that have session_start in whichever script OP intends to use session variable.  I think my answer already covered all aspects of OP's question, but I really wonder what OP meant by "I tried that (tried what, which suggestion?), it wouldn't pick up my username on ANOTHER LINK (that leads to another script?) on my site, with the session_start(); at the top (of which script)"?

drakkarnoir, would you please clarify it?  I suspect now the question is how exactly you wrote your script to follow our suggestions, because normally our suggestions should make it work, and I can't see any aspect that you asked that was not covered by my post above.  It should work, let's get some diagnosis going.
0
 

Author Comment

by:drakkarnoir
Comment Utility
Ok I have 1 page in which I have if-else's evaluating what to display on the users screen. So all I think I would need is the session_start(); on top of the page, since it's always the same page being called index.php?p=somepage like this.

I tried what you said, it would not carry the $username from one page to the other nor the $password. I need to carry these variables because in some restricted sections, I do a query to check the access level of the user...so I do "SELECT * from mytable where username='$username' and password=encrypt('$password','$username')" so you see why I need to keep carrying these vars.

I hope that clears it up.
0
 

Author Comment

by:drakkarnoir
Comment Utility
One section of the same page rather is what I meant by carrying the session vars.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 8

Accepted Solution

by:
inq123 earned 500 total points
Comment Utility
It might not be what you meant, but just to be sure: if you're using $username in your script, you have to declare:

global $username, $password;

if you want to use these two variables in a function even in the same script.  Is that the reason why it didn't work for you.  In detail, imagine this is a complete script of yours:

<?
  session_start();
  $username = $_POST['username'];
  $password = $_POST['password'];
  $_SESSION['username'] = $username;
  test();

  function test()
  {
    global $username, $password;
    print("$username, $password"); # without global above, they won't print
  }
?>
  this is my html code
<?
  global $username, $password;
  print("$username, $password"); # again, without global above, they won't print
?>
0
 

Author Comment

by:drakkarnoir
Comment Utility
Ok everything is working GREAT now. Just one more hurdle:

session.cookie_secure Off Off
session.use_cookies On On

Those are my PHP settings, but it won't restore a session after I close out of the window, and my cookies are on.
0
 
LVL 8

Expert Comment

by:inq123
Comment Utility
That's the default setting -- after you close your window the session is gone.  If you want to change that, you have to set session.cookie_lifetime to what you want.  By default it's set to 0 which means it's gone when browser's closed.  1 means 1 second, 86400 means a day and so on.
0
 
LVL 8

Expert Comment

by:inq123
Comment Utility
So for example, you want your session to be accessible for a day, then just set session.cookie_lifetime to 86400 in your php.ini
0
 
LVL 4

Expert Comment

by:duerra
Comment Utility
>>"duerra, you haven't been reading OP's posts or others' posts carefully :-).  OP said register_globals are ON, also I already suggested don't mix session_register and $_SESSION and that have session_start in whichever script OP intends to use session variable"

Yes, I was just explaining further why you instructed him not to - because by doing so, you're going to break your scripts.
0
 
LVL 8

Expert Comment

by:inq123
Comment Utility
I c.  My bad. :-)
0
 

Author Comment

by:drakkarnoir
Comment Utility
What about if I want to make a checkbox that says "remember me" like EE's?
0
 
LVL 4

Expert Comment

by:duerra
Comment Utility
That would require setting a cookie to the user's machine containing whatever information that you feel necessary to validate their identity.
0
 
LVL 8

Expert Comment

by:inq123
Comment Utility
Two comments:

1. Usually if you want to set a cookie, you use set_cookie function.
2. In your case, it's actually not needed.  What you should do is give user a checkbox, and if they check the box, you let that session stay in effect.  If they uncheck that box and then submit or navigate to another script, then in that script you'd find the checkbox is unchecked, so call session_destroy to get rid of $_SESSION['username'], then it won't be remembered any more.  It'd have same effect than setting another cookie.
0
 

Author Comment

by:drakkarnoir
Comment Utility
Ok guys, works great now! Thanks for both of your inputs...I think I've offically forgotten the word cookie (except milk and cookies) and fallen in love with sessions.

Thank you so so much for all your help, and rock on you guys are contributing a lot to this place :)
0
 

Author Comment

by:drakkarnoir
Comment Utility
Oh and inq123 look for your other thread with the other points, just comment in there and I will accept :)
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now