00:00
00:00
Newgrounds Background Image Theme

LewgusWithFriends just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

Php: Sessions And Cookies

3,560 Views | 11 Replies
New Topic Respond to this Topic

Php: Sessions And Cookies 2006-07-11 17:12:23


PHP: Main

Sessions and cookies are very widely used around the internet. A session can be something as simple as displaying the user's name on the page, and it can do as much as keeping a user logged into a forum (or entire user site). Cookies can keep a user's information stored on their computer, even after the session is stopped. Using them together can be very easy and pretty powerful.

PART 1: Learning Sessions

Sessions are very easy to use. All a session does is store a variable with the server while the session is running. The session is closed when the browser is closed. You start a session using the session_start() function.

<?php
session_start();
?>

Now, of course, that's not all, but that is the most important part of using sessions. You must ALWAYS start the session before you can get any variables from the session. Now, let's put a variable into the session...let's use a username that has been posted from a form on the previous page.

<?php
$username = $_POST['username'];

session_start();
$_SESSION['username'] = $username;
?>

And there you go! Now you can call on the username variable like so...

<?php
session_start();
$username = $_SESSION['username'];
?>

Also, you may have heard of the session_register() function. I don't like to use this one, visit the link to see why, but basically, using my method is more widely accepted.

PART 2: Learning Cookies

Yes, yes, I know there are a few other cookie tutorials. Yes, I know cookies aren't always that great. But this is MY TUTORIAL, so I'll teach what I want >:)

Setting a cookie is pretty easy too...almost as easy as setting up a session. We use set_cookie() to set cookies.
There are 6 parts to set in a cookie...but you only need three to get the cookie to work properly, as the others will fill in default.
Let's set two cookies...one from a username field on a form on the previous page, and one from a password field.

<?php
$username = $_POST['username'];
$password = $_POST['password'];

set_cookie("username", $username, time()+3600);
set_cookie("password", $password, time()+3600);
?>

Now, the cookies' names are username and password, and they both store the correct variables. You can md5 the password if you want...but this is just a quick overview.
Lastly, the time part tells how long until the cookie expires. Here's what you add to the time() for however long you want until the cookie expires.

31536000 - 1 Year
604800 - 1 Week
86400 - 1 day
3600 - 1 hour
60 - 30 minutes
20 - 10 minutes

The other fields are...
- The path the cookie is able to be accessed from, default is the directory (and all under) that the cookie was placed by
- The domain the cookie can be used by (including subdomain)
- Wether or not the cookie is secure

Here's a cookie with all the fields in place...just to show what it looks like. If you want to study up on it, check out the PHP tutorial for it, which is the last link I gave you.

set_cookie("username", $username, time()+3600, "/", ".site.com", 1);

PART 3: Having Cookies and Sessions Talk To Each Other

This is even as simple as the last two steps. Check to see if there are cookies...and if there are, set the session. If not, do the default action to get the information from the user to set the session. We will be using the very amazing isset() function.

<?php
if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$username = $_COOKIE['username'];
$password = $_COOKIE['password'];

session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;

header("Location: http://www.site.com/admin/");
die();
} else {
echo "<form method=POST>
<input type='text' size='30' name='username' />
<input type='password' size='30' name='password' />
<input type='submit' value='Submit!' />
</form>";
// Now just follow steps one and two.
}
?>

PART 4: The Conclusion

This was a simple, bare-bones, easily customizable tutorial. It is meant to be changed and modified to fit your specific project, and to brush over the topics of sessions and cookies.

Please, give any feedback and modifications you can to this tutorial, as that's what's best about PHP: Main!

Response to Php: Sessions And Cookies 2006-07-11 17:15:39


Excellent tutorial!

I can't wait for the next update of PHP Main.

Response to Php: Sessions And Cookies 2006-07-12 06:26:38


Sweet. Good job.

Response to Php: Sessions And Cookies 2006-07-17 11:32:51


Good sessions advices!

Response to Php: Sessions And Cookies 2006-07-17 13:17:34


Thanks for the nice comments :)

Response to Php: Sessions And Cookies 2007-02-24 09:20:17


So, if i wanted to access a session variable I declared on another page, would I type $_SESSION[$variable]?

Response to Php: Sessions And Cookies 2007-02-24 09:27:23


At 2/24/07 09:20 AM, pt9-9 wrote: So, if i wanted to access a session variable I declared on another page, would I type $_SESSION[$variable]?

echo $_SESSION['variable'];

// Don't use the dollar sign, but use quotation marks on both sides.


woop.

BBS Signature

Response to Php: Sessions And Cookies 2007-02-24 09:46:04


Thanks!

Response to Php: Sessions And Cookies 2007-02-24 10:23:28


At 2/24/07 09:27 AM, ApatheticMark wrote: // Don't use the dollar sign, but use quotation marks on both sides.

Actually, I use variables inside of superglobals ALL the time. I wouldn't say not to do that, because it's perfectly fine. For instance, say I have 10 session variables I want to check with the same criteria, why would I do it manually when I could do something like this?

<?php
session_start();
$fields = array('name', 'address', 'email', 'age', 'gender', 'zip', 'country', 'state', 'ngalias', 'currentdate');
foreach($fields as $field) {
if ( true === true ) { // Perform validation here
$_SESSION[$field] = $_POST[$field];
}
}
?>

Something basic like that even warrants that you use variables inside of sessions. It's a common practice, as I (verbosely) stated.

Anywho, I'm surprised to see no one gripe about certain information that was left out of this tutorial. I'm extremely shocked to not see the discussion of session headers and how calling the session_start() function AFTER output will cause errors (unless an output buffer is present).

I know style is personal, but I wouldn't get in the habit of calling session_start() later down in the page as you have shown in this tutorial. It's often considered sloppy and difficult to read if others are modifying your code. Either way, you should definitely make a mentioning of the errors that can be raised if you have output before a call to session_start() is made unless you're using an output buffer. I bet a lot of people will encounter this problem. So here it is:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
In case you can't figure out why you're getting the "headers already sent" error when your page loads, here are some common causes of it:

- The page you're calling session_start() on has output before the function is called
- A required or included page contains output before you call session_start()
- A mixture of both

With that being said, I wouldn't say you have to make sure session_start() is always absolutely first, because I'm not a syntax nazi, and thankfully whoever thought of output buffers weren't either. :-P

Output buffers are explained decently this tutorial but if you're too lazy, I'll go ahead and give an over view, again.

<?php
ob_start();
echo 'loloutput';
session_start();
echo 'lolmoreoutput';
ob_end_flush();
?>

That's perfectly fine, know why? We gotta output buffa dawg. Anyway, calling ob_start() starts the output buffer. So what exactly is an output buffer? What it does is buffer (or temporarily "save") the output on a page. So how does that help? Well, when output is on a page it sends the header to the browser, mainly because if it didn't send the header the browser wouldn't know how to display the text.

Buffering the output delays its delivery until the end of the page (i.e. when you call ob_end_flush()). So yea, there ya go. I'll shut the hell up now like all of you guys are hoping I will.

Kbye.

Merkd.com - It Pays to Play

Earn real money by betting and investing; or, sponsor, challenge, compete,

recruit, communicate, network, earn money playing games, and much more.

Response to Php: Sessions And Cookies 2007-02-24 12:02:09


At 2/24/07 10:29 AM, SpamBurger wrote: What is the point of this if statement? True is always true so there really is no point.
If I am not seeing something, please inform me.

It's not exactly a true = true statement...It's just a placeholder for some other validation statement that you need to replace.


Hello, from the past!

[ PHP: Main ]

BBS Signature

Response to Php: Sessions And Cookies 2007-03-12 16:37:54


what sort of security risk are their with using the sesion thing of wonder. such as is it safe to store the uers passwrod in the session, or somthing like that.

Response to Php: Sessions And Cookies 2007-03-13 03:15:07


The information storaged in the session is only accessible for php, the users can not read it and not change it.


Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.