Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

PHP Forum


You are currently viewing our PHP Forum as a guest. Please register to participate.
Login



Freelance Jobs

Reply
Old 03-05-2009, 05:42 AM php sessions
Knight13's Avatar
Defies a Status

Posts: 10,289
Name: Knight13
Location: Cleveland, Ohio
Trades: 0
I am working on sessions now in php and i am totally lost on what i have to do is their anyone that can explain it in easy steps for me because i just do not get it.
Knight13 is offline
Reply With Quote
View Public Profile
 
 
Register now for full access!
Old 03-05-2009, 05:59 AM Re: php sessions
Average Talker

Posts: 15
Trades: 0
What exactly is confusing you?
GOPalmer is offline
Reply With Quote
View Public Profile
 
Old 03-05-2009, 06:13 AM Re: php sessions
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
Look at the session mechanism like a wallet.
What you put in this wallet can be used in any subsequent page of the site.
It allows you to avoid having parameters passed in the url all along the site.

Basically, either php quto start a session, or you manually start it with
PHP Code:
sesion_start(); 
The name is a bit confusing, because it's starting a session only if none was started before for the given user.
If the user was on a page before, and a session was already started there, it get back the session created before.
Then, you can simply store variables into the (super)array $_SESSION.

Exemple:
index.php:
PHP Code:
<?php
session_start
();  //we tell PHP we want to use sessions
if( (!isset($_SESSION['logged')) || ($_SESSION['logged']!==TRUE){
  
//the member is not identified, we redirect him to the login page
  
header('location:/login.php');
  exit();  
//to prevent further parsing of the script
}
else{
  print 
'Welcome '.$_SESSION['username']."!";
}
login.php (a simple login form):
PHP Code:
<?php
session_start
();
$msg='';
if(
sizeof($_POST)>0){
  
//form posted
  
$user=trim(addslashes($_POST['username']));
  
$pass=trim(addslashes($_POST['password']));
  if(
$user=='admin' && $pass='MasterOfTheWorld'){
    
$_SESSION['username']='The Brain';
    
$_SESSION['logged']=TRUE;
    
    
header('location:/index.php');
    exit();
  }
  else{
    
$_SESSION['username']=NULL;
    
$_SESSION['logged']=FALSE;
    
$msg='Invalid login'
  
}
}
?>
<html>
  <body>
    <form method="post" action="/login.php">
      <input type="text" name="username"/><br/>
      <input type="password" name="password"/><br/>
      <input type="submit" name="submit"/><br/>
    </form>
  </body>
</html>
The index.php will redirect the user to a login page as long as the user is not identified successfuly.
Once the user indetify itself, then he is allowed to access index.php, which greats him.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 03-05-2009, 06:19 AM Re: php sessions
Experienced Talker

Posts: 33
Trades: 0
Firstly a Session tends to only last for 20 min by default this can be changed in the php.ini(i think). So if the user is inactive for 20min the session will be destroyed.

To start you need

PHP Code:
<?php session_start();
at the top of all of you php pages (obviously not your includes just the "main" page)

Once you have done that, treat sessions like php variables, they can every by an array.

To set a session variable do

PHP Code:
$_SESSION['loggedIn'] = true;
$_SESSION['userId'] = $userId
that would be what i'd do for a user login.

If a user visits a page you need to check if they are logged in to do this do

PHP Code:
//make sure the variable is set, can avoid getting error messages
if(isset($_SESSION['loggedIn']))
{
    
//check user is logged in
    
if($_SESSION['loggedIn'])
    {
         
//they are logged in
    
}

When the user logs out the best thing I find to do is destroy the session, however if you still need session items you can unset specific session variables.

PHP Code:
session_unset();
session_destroy(); 
One thing to remember. Session are basic cookies but do not stay on the user computer once they have closed the browser. If you need the user to be remember after they have closed the browser, e.g the "remember me" on many websites. You MUST use cookies, which you set how long they can stay on the users computer.

Hope that help you and makes sense.
__________________

Please login or register to view this content. Registration is FREE

Please login or register to view this content. Registration is FREE
rambo3 is offline
Reply With Quote
View Public Profile
 
Old 03-05-2009, 03:33 PM Re: php sessions
Knight13's Avatar
Defies a Status

Posts: 10,289
Name: Knight13
Location: Cleveland, Ohio
Trades: 0
Ok thanks for the answers guys, i have a few more questions about sessions but before i ask them what do you think is the best way to track users with cookies or sessions.
Knight13 is offline
Reply With Quote
View Public Profile
 
Old 03-05-2009, 03:34 PM Re: php sessions
Junior Talker

Posts: 1
Trades: 0
And use ob_start(); function if you get "Headers already sent..." error somewhere.
smarketing is offline
Reply With Quote
View Public Profile
 
Old 03-05-2009, 04:58 PM Re: php sessions
Experienced Talker

Posts: 33
Trades: 0
I'd use session initially if you want track a current user. You will need cookies for returning visistors, as some people have (including me) a dynamic ip from their isp.
__________________

Please login or register to view this content. Registration is FREE

Please login or register to view this content. Registration is FREE
rambo3 is offline
Reply With Quote
View Public Profile
 
Old 03-05-2009, 05:08 PM Re: php sessions
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
I agree with rambo.
Beside, a session rely on a cookie (if you haven't modified php.ini settings) too.

The session last only for a short while after the user stops being active on the site (remember that due to the web way of working, you cannot know when a user have left your site. You can only know for how long since he last accessed a page).

Thus, a cookie is the only way you have to identify a user comming back to your site, without him identifying himslef.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 03-05-2009, 06:42 PM Re: php sessions
Knight13's Avatar
Defies a Status

Posts: 10,289
Name: Knight13
Location: Cleveland, Ohio
Trades: 0
Well how would i use cookies to track someone is it basically the same as sessions?
Knight13 is offline
Reply With Quote
View Public Profile
 
Old 03-05-2009, 06:52 PM Re: php sessions
racer x's Avatar
Ultra Talker

Posts: 457
Name: Randy
Location: Northern Wisconsin
Trades: 0
I am currently following a great video tutorial on php. I think the link below was the day he did sessions and cookies.

Here's the link: http://blog.themeforest.net/screenca...nto-php-day-9/

I highly recommend checking it out.
This series is good to:
http://www.killerphp.com/videos/php-sessions-part1.php
racer x is offline
Reply With Quote
View Public Profile Visit racer x's homepage!
 
Old 03-05-2009, 07:06 PM Re: php sessions
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
Quote:
Originally Posted by Knight13 View Post
Well how would i use cookies to track someone is it basically the same as sessions?
:-)
Almost.

A cookie is a small file containing an information that a web site store in the user browser.
The PHP session mechanism generate a session id at the first session_start() call, and save this id in a cookie that last until the user browser is closed.

PHP then is relying on the cookie to restore the designated session id to the right user on each page, but they are not the same.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 03-05-2009, 08:08 PM Re: php sessions
Knight13's Avatar
Defies a Status

Posts: 10,289
Name: Knight13
Location: Cleveland, Ohio
Trades: 0
So using a cookie would be better than using session?
Knight13 is offline
Reply With Quote
View Public Profile
 
Old 03-05-2009, 09:06 PM Re: php sessions
NullPointer's Avatar
Will Code for Food

Posts: 2,815
Name: Matt
Location: Irvine, CA
Trades: 0
Quote:
Originally Posted by Knight13 View Post
So using a cookie would be better than using session?
That depends on the situation.

Sessions should be used to track information about a user while they navigate your site. Things like their username (not password!) user id, email address etc..

Cookies are better suited for retriving information from a user after they have left your site. This is how the remember me function on a lot of sites is implemented. If a users opts for your site to "remember" him then a cookie is set containing his username or some other identifying information so the site can log him in automatically. This is just a rough example.

The information in a session is stored server side, while cookies are stored client side. As tripy pointed out sessions rely on cookies to identify the user that the session belongs to.
__________________

Please login or register to view this content. Registration is FREE
|
Please login or register to view this content. Registration is FREE
|
Please login or register to view this content. Registration is FREE
|
Please login or register to view this content. Registration is FREE

Last edited by NullPointer; 03-05-2009 at 09:09 PM..
NullPointer is online now
Reply With Quote
View Public Profile Visit NullPointer's homepage!
 
Old 03-05-2009, 09:12 PM Re: php sessions
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
They have different use.
Session is meant for storing values that are used during a regular browsing of the site.
Cookies are used to keep transient values that will be reused at the next visit of the user to your site.

Just keep in mind that:
1) cookie can be forged and modified
2) the user can clean up his cookie storage
3) there is a limited size allowable for the cookies, so you cannot store large amount of datas. The number of cookies is limited too

With that in mind, you code must not rely on cookies, but be able to get some values from them.
Always give a default value to the variables you need in your script, and then get the value from the cookie if it exists.
Cookie values are as unsafe than form value.

The "regular" usage of the cookies is generally to save a hashed value.
When the user comes to the site, that hashed value is compared to a saved hased value in the db, and if something matches, the user is automagically logged in by the site.
Never store username or password or important values in a cookie. It's just a text file that the user can open in notepad, on his computer.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 03-05-2009, 09:24 PM Re: php sessions
Knight13's Avatar
Defies a Status

Posts: 10,289
Name: Knight13
Location: Cleveland, Ohio
Trades: 0
So websites need to use both cookies and sessions?
Knight13 is offline
Reply With Quote
View Public Profile
 
Old 03-06-2009, 02:26 AM Re: php sessions
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
They don't need, but usually, they do.

If php detects that no cookie is available, or if you instruct him to do so, it can adds an "phpsessid=abcdef1234567890" parameter to every url of your pages, to transmit the session id from page to page.
And a simple site can avoid session usage.

They are just tools, that are open for you to take advantage from.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 03-06-2009, 04:13 AM Re: php sessions
Knight13's Avatar
Defies a Status

Posts: 10,289
Name: Knight13
Location: Cleveland, Ohio
Trades: 0
So what do i exactly put into a cookie that i send to a website? is their certain information i need to put into one or are cookies made all the same?
Knight13 is offline
Reply With Quote
View Public Profile
 
Old 03-06-2009, 04:28 AM Re: php sessions
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
Quote:
So what do i exactly put into a cookie that i send to a website?
It goes the other way.
A web site save a cookie in the browser, but you cannot manage what cookie is sent to the server.

As for what to put into the cookie:
Quote:
The "regular" usage of the cookies is generally to save a hashed value.
When the user comes to the site, that hashed value is compared to a saved hashed value in the db, and if something matches, the user is automagically logged in by the site.
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Old 03-06-2009, 06:35 AM Re: php sessions
Knight13's Avatar
Defies a Status

Posts: 10,289
Name: Knight13
Location: Cleveland, Ohio
Trades: 0
How is a hashed value put into the cookie?
Knight13 is offline
Reply With Quote
View Public Profile
 
Old 03-06-2009, 07:03 AM Re: php sessions
tripy's Avatar
Do not try this at home!

Posts: 3,621
Name: Thierry
Location: I'm the uber Spaminator !
Trades: 0
I always have used this:
PHP Code:
<?php
$hash
=md5(uniqid(rand(),true));
it generate an 128 character random string.
I often generate this value when a user logs in successfully, put it in a cookie and save it in the db with the user infos.

When the user comes back, I check if the cookie exists.
If it does exists, I try to locate the hash in the db, and if I found it, I log him without asking username/password.
Of course, the auto login re-generate a new hash.

The hash is saved in a cookie via the setcookie() function
http://www.php.net/manual/en/function.setcookie.php
__________________
Only a biker knows why a dog sticks his head out the window.
tripy is offline
Reply With Quote
View Public Profile Visit tripy's homepage!
 
Reply     « Reply to php sessions

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.70945 seconds with 12 queries