Simple use of cookies with php

With php you can set a “cookie” in a users session, which stores a small amount of data on the users computer.

Cookies can be useful to check if the user recently logged in to your webpage,
recently visited your webpage, or such.

With the use of cookies are pretty simple…

Heres how you create the cookie:

1
2
3
<php
setcookie( "user", $_SERVER['REMOTE_ADDR'], time()+3600 );
?>

That sets the cookie name to ”user”, the value to the users Ip adress, and  the time value to, the current time plus 3600 seconds ( 1 hour in the future).

Later on you can check if the cookie is set, by simply using the “isset” function like this:

1
2
3
4
5
6
7
<?php
 
if (isset($_COOKIE["user"]))
 echo "Welcome back " . $_COOKIE["user"] ;
 else
 echo "Welcome guest";
?>

More information about cookies can be found here.

Leave a Reply


To prove that you're not a bot, enter this code
Anti-Spam Image

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>