Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

URGENT: PHP sessions question

Posted on 2003-11-02
21
320 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
ID: 9667823
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
ID: 9667838
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
ID: 9667840
Oh and global_registers are ON
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 17

Expert Comment

by:Suat Ozgur
ID: 9668001
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
ID: 9668094
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
ID: 9668178
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
ID: 9669327
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
ID: 9670346
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
ID: 9671849
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
ID: 9671868
One section of the same page rather is what I meant by carrying the session vars.
0
 
LVL 8

Accepted Solution

by:
inq123 earned 500 total points
ID: 9672130
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
ID: 9672917
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
ID: 9672984
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
ID: 9672996
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
ID: 9673496
>>"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
ID: 9673707
I c.  My bad. :-)
0
 

Author Comment

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

Expert Comment

by:duerra
ID: 9674594
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
ID: 9675340
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
ID: 9679565
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
ID: 9679574
Oh and inq123 look for your other thread with the other points, just comment in there and I will accept :)
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

829 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