PHP Sessions and Cookies Tutorial
Ranked #2,434 in Internet, #141,543 overall
What are Sessions and Cookies?
Sessions
How are sessions used?
<?php
session_start(); //enable the use of sessions
$_SESSION['my_session'] = "I created my own session!";
?>
Example of usage
Now we know how to create a session so let's make an actual simple system with it. We'll create a very small login system ( well, the part of the system that remembers a valid login ). It consists of 3 files:
- login.php
creates a session that indicates that a user is logged in - logout.php
removes the session that indicates that a user is logged in - members.php
a members-only page that checks whether the user is logged in
login.php
<?php
session_start();
$_SESSION['loggedin'] = TRUE; //indicate that the user is logged in
?>
<?php
session_start();
$_SESSION['loggedin'] = FALSE; //indicate that the user is no longer logged in
?>
<?php
session_start();
if($_SESSION['loggedin'] == TRUE) { //if the user is logged in
echo "Welcome to the members area!";
}else{ //user is not logged in
echo "Oops... you have to be logged in to view this part of the website.";
}
?>
Some very simple, yet effective usages of sessions we've seen above. Although this is of course not a full login system, but it illustrates how a login system works. Soon I'll create a tutorial on how to create a full login system for those who're interested.
Note: Some login systems use cookies instead of sessions ( or allow both ) because they can be remembered for a longer term, and nowadays most of the browsers allow them ( pretty much all of them ). But still: the user of the browser can see the cookies and remove or disable them.
Cookies
How to use cookies?
<?php
// creates $_COOKIES['my_cookie'] = "my own cookie!" and does not expire
setcookie("my_cookie", "my own cookie!");
//creates $_COOKIES['another_cookie'] = "my second cookie!" and expires in 1 day (60*60*24 seconds)
setcookie("another_cookie", "my second cookie!", time()+(60*60*24));
?>
You might also like ...
Related Products (Amazon)
Related Products (eBay)
by webcodez
"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."
webcodez
GameHeroes
more »
- 21 featured lenses
- Winner of 14 trophies!
- Top lens » PHP & MySQL Poll System Tutorial
Explore related pages
- PHP & MySQL Poll System Tutorial PHP & MySQL Poll System Tutorial
- PHP & MySQL Login System Tutorial PHP & MySQL Login System Tutorial
- PHP & MySQL Visitors Counter Tutorial PHP & MySQL Visitors Counter Tutorial
- PHP basics tutorial PHP basics tutorial
- PHP Banner Rotator Tutorial PHP Banner Rotator Tutorial
- PHP POST and GET Variables Tutorial PHP POST and GET Variables Tutorial