Using Cookie Authentication PHP

Store authentication status in a cookie or as part of a session. When a user logs in
successfully, put their username in a cookie. Also include a hash of the username and a secret
word so a user can't just make up an authentication cookie with a username in it:

$secret_word = 'if i ate spinach';
if (pc_validate($_REQUEST['username'],$_REQUEST['password'])) {
setcookie('login',
$_REQUEST['username'].','.md5($_REQUEST['username'].$secret_word));
}
 Discussion
When using cookie authentication, you have to display your own login form:
<form method="post" action="login.php">
Username: <input type="text" name="username"> <br>
Password: <input type="password" name="password"> <br>
<input type="submit" value="Log In">
</form>
You can use the same pc_validate( ) function from the Recipe 8.10 to verify the username
and password. The only difference is that you pass it $_REQUEST['username'] and
$_REQUEST['password'] as the credentials instead of $_SERVER['PHP_AUTH_USER'] and
$_SERVER['PHP_AUTH_PW']. If the password checks out, send back a cookie that contains a
username and a hash of the username, and a secret word. The hash prevents a user from
faking a login just by sending a cookie with a username in it.
Once the user has logged in, a page just needs to verify that a valid login cookie was sent in
order to do special things for that logged-in user:
unset($username);
if ($_COOKIE['login']) {
list($c_username,$cookie_hash) = split(',',$_COOKIE['login']);
if (md5($c_username.$secret_word) == $cookie_hash) {
$username = $c_username;
} else {
print "You have sent a bad cookie.";
}
}
if ($username) {
print "Welcome, $username.";
} else {
print "Welcome, anonymous user.";
}
If you use the built-in session support, you can add the username and hash to the session and
avoid sending a separate cookie. When someone logs in, set an additional variable in the
session instead of sending a cookie:
if (pc_validate($_REQUEST['username'],$_REQUEST['password'])) {
$_SESSION['login'] =
$_REQUEST['username'].','.md5($_REQUEST['username'].$secret_word));
}
The verification code is almost the same; it just uses $_SESSION instead of $_COOKIE:

unset($username);
if ($_SESSION['login']) {
list($c_username,$cookie_hash) = explode(',',$_SESSION['login']);
if (md5($c_username.$secret_word) == $cookie_hash) {
$username = $c_username;
} else {
print "You have tampered with your session.";
}
}
Using cookie or session authentication instead of HTTP Basic authentication makes it much
easier for users to log out: you just delete their login cookie or remove the login variable from
their session. Another advantage of storing authentication information in a session is that you
can link users' browsing activities while logged in to their browsing activities before they log in
or after they log out. With HTTP Basic authentication, you have no way of tying the requests
with a username to the requests that the same user made before they supplied a username.
Looking for requests from the same IP address is error-prone, especially if the user is behind a
firewall or proxy server. If you are using sessions, you can modify the login procedure to log
the connection between session ID and username:
if (pc_validate($_REQUEST['username'],$_REQUEST['password'])) {
$_SESSION['login'] =
$_REQUEST['username'].','.md5($_REQUEST['username'].$secret_word));
Related Posts:
  • PHP Expressions An expression is the basic building block of the language.  Anything with a value can be thought of as an expression.  Examples include: 5 5+5 $a $a==5 sqrt(9) By combining many of these basic expressions, you… Read More
  • Php-Configuration Control Through .htaccess The .htaccessfile is very powerful and can control more than just URL structure. For instance, you can control PHP configuration options using the .htaccessfile. To increase the memory allotted to PHP use this command: php_v… Read More
  • URL rewriting-various exercises-seo  Installing mod_rewrite Testing mod_rewrite Working with regular expressions Rewriting numeric URLs with two parameters Rewriting keyword-rich URLs Building a link factory Pagination and UR… Read More
  • how Installing mod_rewrite localhost If you’ve installed Apache yourself, read on. Because of its  popularity, mod_rewrite is now included with all common  Apache distributions. If desired, you can verify if your Apache installation has the mod_rewr… Read More
  • var_dump and print_r -PHP-standard Functions like var_dump and print_r are also invaluable when debugging var_dump var_dump functions displays information about variables in a simple, readable  format. This function is very useful when debugging—p… Read More
  • php-Dynamic Variables Sometimes it is useful to set and use variables dynamically.  Normally, you assign a variable like this:  $var = "hello";   Now let's say you want a variable whose name is the  value of the $var va… Read More
  • what is CodeIgniter Helpers? Helpers, as their name implies, help you with specific tasks. Unlike libraries, helpers are not object -oriented but procedural in nature. Each helper contains one or more functions, each focusing on a specific task, with ze… Read More
  • Visualize Traffic with DIY Vector you will learn how to create your own traffic chart using the incredibly cool Canvas framework, which can produce vector graphics and animations with a little bit of HTML and JavaScript. All code referenced in this hack i… Read More
  • Building Dynamic Images-PHP You want to create an image based on a existing image template and dynamic data typically text). For instance, you want to create a hit counter. Load the template image, find the correct position to properly cente… Read More
  • codeigniter routes page The  routes.php filelets you remap URI requests to specific controller functions. For example, you may have a controller named sitewith a function named index. The URI for this controller/function combination might be… Read More
  • security to POST-PHP $_POST  POST-method variables. Form field data from regular  POST-method forms.   PHP automatically creates variables for all the data it receives  in an HTTP request. This can include GET data, POST … Read More
  • PHP while Loop PHP while Loop with code while - loops run  a set of code as  the  condition is true. Basic Syntaxwhile (condition){    code for executed;}<?php$k=1;while($k<=5) {  echo "The numbe… Read More
  • How to Enable mod_rewrite at Server mod_rewrite may not be enabled by default in your Apache configuration. To make sure,open the Apache configuration file, named httpd.conf. The full path of the file will be \Program Files\xampp\apache\conf\httpd.conf. Open … Read More
  • Sorting Arrays-PHP PHP supports a variety of ways to sort an array when  I say sort, I am referring to an alphabetical sort if it is a string,  and a numerical sort if it is a number. When sorting an array,  you must k… Read More
  • MySQL with php The basic steps of performing a query, whether using the mysql command-line tool or PHP, are the same:Connect to the database.Select the database to use.Build a SELECT statement.Perform the query.Display the results. Wh… Read More