Home » Code, PHP Functions, Scripts, Tutorials

PHP Cookies with Login – setcookie()

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:

setcookie($name, $value, $expire, $path, $domain);

So if you want to create a cookie for someone’s status that will last one day, the code would look something like this:

// name = status
// expire = current timestamp plus 24 hours
// path = current path "/"
setcookie("status","user status here",time()+(3600*24),"/");

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

<?php
// function.php

function run_login_form($username,$password){
$username = trim(addslashes($username));
$password = md5(trim($password));

$sql = mysql_query("SELECT userid FROM users WHERE username = '$username' AND password = '$password' LIMIT 1");
if(mysql_num_rows($sql) > 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;
}

}
?>

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

<html>
<head>
<title>PHP Login / Logout</title>
</head>
<body>
<form action="login.php" method="post">
Username: <input type="text" name="username" maxlength="25" /><br/>
Password: <input type="password" name="password" maxlength="40" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Now on login.php we include that function and run it with the submitted username and password.

login.php

<?php
// login.php

include("function.php");

if($_POST["submit"]){

$login = run_login_form($_POST["username"],$_POST["password"]);
if($login){
echo "Login successful! Welcome back!";
} else {
echo "Login unsuccessful! Please try again.";
}

}

?>

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.

<?php
// index.php continued

if($_GET["do"] == "logout"){

if($_COOKIE["userid"] && $_COOKIE["username"]){
// user is logged in, now log them out!

// set the cookies to a time less than the current timestamp
setcookie("userid","",time()-3600,"/");
setcookie("username","",time()-3600,"/");
}

}

?>

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.

0

Popularity: 9% [?]

Share/Bookmark this!

30 Comments

Leave a reply

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

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>

This is a Gravatar-enabled weblog. To get your own globally recognized avatar, please register at Gravatar.

Side Notes

This entry was posted by on November 5, 2009 at 10:48 PM and filed under Code, PHP Functions, Scripts, Tutorials category.

You can add your comments or trackback from your own site. To keep you updated to the latest discussion, you can subscribe to these comments via RSS.

Recent Entries

Pages

Recent Comments

Resources

Questions & Answers

Just started! Have not answered any questions.

Tag Cloud

background body CSS database date dropdown email error_reporting favicon file filesize form format function global hosting HTML image Javascript limit link linkbar mysql numbers online option ordinalize pagination pattern photoshop PHP resize rows script search snowing stylesheet switch table thumbnail time timestamp upload validate variables

Sponsors