A cookie is a small file that the server embeds on the user’s computer. This data is sent and recieved with each browser that is used to view a page using cookies.
To create a cookie in PHP use the setcookie() function. Here is its syntax:
[code lang=”php”]
setcookie($name, $value, $expire, $path, $domain);
[/code]
So if you want to create a cookie for someone’s status that will last one day, the code would look something like this:
[code lang=”php”]
// name = status
// expire = current timestamp plus 24 hours
// path = current path “/”
setcookie(“status”,”user status here”,time()+(3600*24),”/”);
[/code]
So let’s say we want to create a cookie for every user that logs in and have it last for 12 hours. We need to run a login form and validate the login details to match someone on our database, and then create the cookies and set them to a specific time interval. Let’s make a function for this on function.php:
function.php
[code lang=”php”]
0){
$row = mysql_fetch_assoc($sql);
// User found, now let’s create the cookies for the user!
if(!$_COOKIE[“userid”] && !$_COOKIE[“username”]) {
setcookie(“userid”,$row[“userid”],time()+(3600*12),”/”);
setcookie(“username”,$username,time()+(3600*12),”/”);
}
return true;
} else {
return false;
}
}
?>
[/code]
Now if you have a simple form with two inputs, one for username and password, you can send these to a login page which will run the above function to validate and check the login. We’ll put this form on our index.php:
index.php
[code lang=”html”]
[/code]
Now on login.php we include that function and run it with the submitted username and password.
login.php
[code lang=”php”]
[/code]
Now we’ve made the user logged in. Basically we checked the mysql database for a user with those login details and upon finding a match, we created two cookies for that user. One being their userid (an ID we keep in our database for each user) and the other being their username.
So what if the user wants to log out? This is very easy when dealing with simply erasing the cookies we made. We place the following code on our index.php page.
[code lang=”php”]
[/code]
Now when the user visits index.php?do=logout it will run this logout code. If the cookies are found, it erases them and they will be treated as a guest based on how your script treats users without these cookies. This way we can check each user on every page they visit for these cookies to tell if they are a registered and logged in user or a guest.