FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


$_COOKIE and $_SESSION help needed!





bladesage
Hello once again to all!

Well, it seems (to me at least) that I've been both on the giving and receiving ends for help in scripting. However, now I am dangling in the needy end for help in scripting PHP.

I need to know everything (please, EVERYTHING) about sessions, cookies, and session cookies. The more info, the better.

I know everything is quite a bit, but I figure that if even 1/32 of the PHP scriptors on Frihost tell me like two things, I'll have all the info I need.

Mostly, I want to have my users login, and be logged in automatically using cookies. I know that PEAR can help a lot, but it's much more fun to just make a simple system for it myself. Don't tell me to look in php.net or phpfreaks, or anything like that, as I already have (not to mention all the major search engines).

I already have the tables, and people can login and everything, but then they have to again every time they go to a different page. This is frustrating.

I have heard that cookies are more secure than sessions, but I want to know how to use both, as I also heard they make a great combo.

Thanks!
mathiaus
I use a combination. Sessions for everyone using the site and cookies for those wanting to rember their details, converted to sessions when they enter the site.

I'm rather busy so I hope you'll excuse my laziness in just posting some functions being worked on Smile

Auto_login function
Code:
function auto_login($connector, $settings) {
   if ($result = $connector->query('SELECT * FROM `'.$settings['dbprefix'].'users` WHERE `username`=\''.$_COOKIE[$settings['cookieprefix'].'username'].'\' AND `password`=\''.$_COOKIE[$settings['cookieprefix'].'password'].'\'')){

      //Get an array containing the resulting record
      $row = $connector->fetchArray($result);
      // asign collected values to sessions
      $_SESSION['loggedin'] = true;
      $_SESSION['uid'] = $row['uid'];
      $_SESSION['username'] = $row['username'];
      $_SESSION['group'] = $row['group'];
      $_SESSION['skin'] = $row['skin'];
      $_SESSION['language'] = $row['language'];
         
   } else
      logout($settings);
   
}


Auto login - do we call the function?
Code:
if(isset($_COOKIE[$settings['cookieprefix'].'username']) && isset($_COOKIE[$settings['cookieprefix'].'password']) && !isset($_SESSION['loggedin'])) {
   if($_COOKIE[$settings['cookieprefix'].'username'] && $_COOKIE[$settings['cookieprefix'].'password'] && !isset($_SESSION['loggedin'])) {
      include($temppath.'includes/functions_user.php');
      auto_login($connector, $settings);
   }
}


login
Code:
function check_details($details, $connector, $settings) {
   $username = $details['username'];
   $password = md5($details['password']);
   $rememberme = $details['remember'];

   $errors=0;
   // if no username error
    if(empty($username)) {
      $message = "lang_error_noname";
      $errors ++;
   // elseif - we dont want to overwrite error
   // no password then show an error
   } elseif(empty($details['password'])) {
      $message = "lang_error_nopass";
      $errors ++;
   }
   
   
   // if we can find someone with those details their correct
   // notice check errors = 0, we dont want to overwrote the error!
    if ($errors==0) {
      $result = $connector->query('SELECT * FROM `'.$settings['dbprefix'].'users` WHERE `username`=\''.$username.'\' AND `password`=\''.$password.'\' AND `val`=\'1\'');
      $row = $connector->fetchArray($result);
      
      // If there is no result
      if($row != false) {
         // set session vars for feteched data
         $_SESSION['loggedin'] = true;
         $_SESSION['uid'] = $row['uid'];
         $_SESSION['username'] = $row['username'];
         $_SESSION['group'] = $row['group'];
         $_SESSION['skin'] = $row['skin'];
         $_SESSION['language'] = $row['language'];
         $_SESSION['justloggedin'] = true;
         
         // Does the user want to be remembered? (set cookies)
         if($rememberme) {
            // set the cookies
            setcookie($settings['cookieprefix'].'username', $row['username'], time()+60*60*$settings['cookie_expire'], '/', $settings['cookie_domain']);
            setcookie($settings['cookieprefix'].'password', $password, time()+60*60*$settings['cookie_expire'], '/', $settings['cookie_domain']);
         }
         
         // redirect to the same page so that we get a nice logged in message
         header('Location:'.$settings['siteUrl'].'user.php');
      
      // this is if no account is found
      } else {
      $message = "lang_error_noaccount";
      }
   }
 
    return $message;
}



Obviously this is all coded for something else but its commented so I hope you'r able to get the jist of it. I wont explain anything here unless you ask for me to. Very Happy
hexkid
bladesage wrote:
I need to know everything (please, EVERYTHING) about sessions ...

Add this lines of code to all your scripts, right at the top, before anything else even DOCTYPE
Code:
<?php
session_start();
?>

That's it! That's everything you need to know about sessions.

bladesage wrote:
... cookies ...

Some clients may have cookies disabled.
Cookie values are not guaranteed to be what you expect (the client can change them at will).
That's it! That's everything you need to know about cookies.

bladesage wrote:
... session cookies.

Session cookies get automatically deleted by the browser when it is closed.
That's it! That's everything you need to know about session cookies.


But I'll give you a few more thoughts ...
bladesage wrote:
Mostly, I want to have my users login, and be logged in automatically using cookies.

I prefer users to login and be logged in automatically using session variables. I don't really care for auto-login with cookies, but you might want to do that.

bladesage wrote:
I already have the tables, and people can login and everything, but then they have to again every time they go to a different page. This is frustrating.

Use session variables to know (errr... I mean, have a strong indication) that this session belongs to a logged in user.
Code:
// ...
// user is logged in with your existing script
// ...
// add info to a session variable
$_SESSION['loggedin']=1;

And, in all pages that require a login, before doing the login check the session variable
Code:
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin']===1) {
  // no need to login
} else {
  // need to login
}



bladesage wrote:
I have heard that cookies are more secure than sessions

Wrong! cookies are under the user control; session variables are under the programmer control.

bladesage wrote:
but I want to know how to use both, as I also heard they make a great combo.

http://www.php.net/manual
Yeah, yeah ... I know Smile
deepak
For security reasons, please dont save password in cookie, best it to use php session or a random key which detects user. Another good option like all webservices do is ask for password and detect username, its simple and secure.
kawkazEE
i prefer using php sessions, say on my first page i let the client logged in and i want to maintain the state.

firstpage.php
<?php
session_start();

if ($_POST['username'] == 'myuser' && $_POST['password'] == 'mypass') {
$_session['login'] = 'true';
}

...some HTML form...

?>

secondpage.php
<?php
if (isset($_session['login']) && $_session['login'] == 'true') {
You are still logged in...
} else {
You need to login to view this page.
}
?>

hope this helps... Laughing Laughing Laughing
Simulator
Sessions are easier to set than cookies as all you need is:
Code:
$_SESSION["EDITABLE-NAME"] = "VALUE";



Where as cookies need:
Code:
setcookie("EDITABLE-NAME", "VALUE");


There are more settings to "setcookie" that you can add, but they are not needed.
There is one thing to note though with sessions, and that is all you files that use a session MUST have:
Code:
session_start();

Otherwise all you'll get is an error, IT MUST BE PLACED BEFORE ANY HTML TAGS ARE PLACED
SlowWalkere
I had this very same problem yesterday. In case the responses here haven't covered everything, check out http://www.hudzilla.org/phpbook/read.php/10_0_0 (Sessions and Cookes from Practical PHP Programming). It's a good overview of how to use cookies and sessions, and you'll need to use both for what you want to do.

In order to keep users logged in as they travel around your site, you need to use sessions. Basically you call the session_start() function, which will automatically set up a session cookie to identify the user as long as the browser stays open. As mentioned before, this function needs to be called before anything else in the file, or you'll get an error. So start the PHP section on line one and go from there. From then on, you have access to the $_SESSION[] variable, which you can fill with whatever you want. In your case, you'll want to make $_SESSION['loggedin'] variable, or some such thing.

What I ended up doing was creating a small php file that I include at the top of every file to call session_start(), check if the user is still logged in, and other little things.


In order to have users log in automatically when they show up on your site, you'd need to use regular cookies. I haven't actually worked this part out, but the concept is pretty similar. You initialize the cookies, set a cookie on the user's machine, and when they come back you read it in. Compare that info against the log-in information in the server. If it's correct, set your $_SESSION['loggedin'] and you're good to go. This would be a good bit of code to throw into a file and include at the top (along with the session initialization).

On a side note, someone commented that you shouldn't leave passwords in cookies on the user's computer. Is that because it gets sent and stored unencrypted? Because in that case you can store the jumbled password (using md5, or whatever you use to jumble passwords before checking against your database). As long as the user asks to have his password saved, I don't see anything wrong with storing it in a cookie on his computer.

- Walkere
codeman
Since we're talking about sessions and things... I have a question myself.

Is there any way to make the sessions last longer... sessions seem to end rather quickly on my site (left unattended of course, not while actively browsing)
Rhysige
Actually extending the session length I think theres a way.. better idea is to use cookies Smile securely ofcourse so they cant be tampered with/stolen
bladesage
codeman wrote:
Since we're talking about sessions and things... I have a question myself.

Is there any way to make the sessions last longer... sessions seem to end rather quickly on my site (left unattended of course, not while actively browsing)


Right after (or maybe before, I'm new to sessions Razz) the session_start() function in each page, add
Code:
ini_set("session.cookie_lifetime", 3600);


Change 3600 to the number you want it to last in seconds. By default, the session cookie will be deleted when the browser is closed (or after a certain amount of time has passed since the last time the session was started).
Related topics
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.