Hi to all,

I need to know how to use the cookie in php,my problem is that when i clicked the log-out.and then i will go to my browser and click the back button.it will go back to the user where it is still logging in.but what i want is that, when i click the back button of the browser it will go to my log in page and it will asked to input username and password.can you help me on this i am
still learning on this.Thank you in advance.

here is my code

log-in.php

<?php

   include_once ('condb.php');

   $expire_time = time() + 60; 
   setcookie("name",$expire_time);   

   if (ISSET($_POST['login']))
    {
       $txtusername = $_POST['txtusername'];
       $txtpassword = $_POST['txtpassword'];

       $sql = "SELECT name,password from cookie_tbl where name = '$txtusername' and
               password = '$txtpassword'";

        $result= mysql_query($sql);

       if(mysql_num_rows($result)>0)
           header('location:userlogin.php');              
       else
         echo "invalid username and password";  

       mysql_close();        
    }

 ?>

  <html>
   <title>login</title>
   <body>
      <h1>log-in page</h1>
      <form method = "post">
        <table border="2">
          <tr>
            <td>Name:</td>
            <td><input type="text" name ="txtusername"></input></td>
          </tr>
          <tr>
            <td>Password:</td>
            <td><input type="text" name="txtpassword"></input></td>
          </tr>
          <tr >
           <td></td>
            <td>
              <input type="submit" name="login" value="login"></input>
              <input type="reset" value="cancel"></input>
            </td>
          </tr>
      </form>
   </body>
  </html>

userlogin.php

<html>
  <h1>user login</h1>
   <form action ="userlog-out.php" method ="post" >
    <div style = "color:red;">
     <?php echo 'Welcome' .  $_COOKIE ["name"]; ?>
    </div> 
     <input type="submit" name="logout" value ="log out">
  </form>
</html>

userlog-out.php

   <?php
       $expire_time = time() - 60; 
       setcookie("name",$expire_time);   

   ?>


<html>
  <title>log-out</title>
  <body>
  <h1>user log-out</h1>

     <h2>YOu have successfully log-out.</h2>
     <a href="login.php">Click here to Login</a>
  </body>
</html>

I usually set my cookies like below. Hopefully, this will help you figure out your issue.

// Use to set cookie session for domain.
$cookiedomain = $_SERVER['SERVER_NAME']; 
$cookiedomain = str_replace('www.', '', $cookiedomain);

if(isset($_POST['remember_me'])){
    setcookie("application_cookname", $_SESSION['username'], time()+60*60*24*365, "/", "." . $cookiedomain);
    setcookie("application_cookpass", md5($_SESSION['password']), time()+60*60*24*365, "/", "." . $cookiedomain);
}

Hi joshmac,

Thank you for the reply,is it necessary to use the $_SERVER?,what doest the str_replace?

Thank you in advance

you don't check if the user is actual loged-in in userlogin.php
I would use $_SESSION insted of cookie

@jemz, you are not setting the cookie domain in your code so no it is not necessary to use $_SERVER. If your domain is www.example.com, the str_replace will replace www. with nothing (''). But again, it doesn't seem like you are setting a cookie domain, so all of that info can be stripped.

@joshmac,Thank you for the reply,yes i have no domain yet,i just want to practice to know how to use cookie
why is my code did not work?every time i log-out and press back button of browser it will display the user
loggin in or i mean the user is still loggin in.can you help me please on this.

Thank you in advance.

@pzuurveen,i have not yet know the difference between the session and the cookie,since i am still learning
on this i want to know first how the cookie will work...

@pzuurveen, by the way how do i checked that if the user is actual loged-in?can you help me on this
please.Thank you in advance

what'happenig:

login.php
login --> userlogin.php
logout --> userlog-out.php
back --> userlogin.php and because you don't check just display the page

what you need to do is send a cook variable to the nexpage:

if(mysql_num_rows($result)>0)
   {
   $_COOKIE['isValidUser']=True; 
   header('location:userlogin.php');
   }
else
    echo "invalid username and password";

in userlogin.php
check on this variable

this is not secure for a passwoord system because users can just edit these cookies and get access even if they are not a member of youre site

@pzuurveen, hi thank you for the reply.the code that you show to me where should i put that in my userlogin.php?.,can i ask is 'isValidUser' a variable or a reserved word in php.

By the way how can users edit the cookies,i really don't how to edit the cookies,thank you for sharing this
idea...i appreciated it.

how i standardly do logins is like this:

<?php 
if(ISSET($_POST['login'])){
    $txtusername = $_POST['txtusername'];
    $txtusername = str_replace("'",'',$txtusername);
    $txtusername = str_replace('"','',$txtusername);
    $txtpassword = $_POST['txtpassword'];
    $txtpassword = str_replace("'",'',$txtpassword);
    $txtpassword = str_replace('"','',$txtpassword);

    $sql = "SELECT `user_id` FROM cookie_tbl where name = '$txtusername' and
               password = '$txtpassword'";
    $result= mysql_query($sql);
    if($result !== false && mysql_num_rows($result)>0){
        $userdata = mysql_fetch_assoc($result);
        $token = md5(rand());
        //should check if token already exists in table and make a new one if it does
        //otherwise a user could login as someone else if the token happens to match(unlikely)
        $tokenQuery = "UPDATE `cookie_tbl` SET `token` = '{$token}' WHERE `user_id` = {$userdata['user_id']}"; 
        if(mysql_query($tokenQuery)){
            setcookie('token',$token,time()+(60*60*8),'/');
            header('location:userlogin.php');
        }else{
            echo "error setting token";
        }

    }else{
        echo "invalid username and password";    
    }
}
?>

The on each page of the site i add a required include like so:

-> index.php

<?php
require_once 'app.php';

if($appData['login']){
    //logged in
    echo "Welcome back <span style='color:{$appData['some_preference']};'>{$appData['user_name']}</span>";
}else{
    header('Location: userlogin.php');
}
?>

then the included file checks if the user is logged in or not and pulls some data you might want to personalise the site:

-> app.php

<?php 
$appData = array();
if(ISSET($_COOKIE['token']) && ctype_alnum($_COOKIE['token'])){
    $checkTokenQuery = "SELECT `user_id`,`user_name`,`some_preference` FROM `cookie_tbl` WHERE `token` = '{$_COOKIE['token']}";
    $chkResult = mysql_query($checkTokenQuery);
    if($chkResult !== false && mysql_num_rows($chkResult) == 1){
        $appData = mysql_fetch_assoc($chkResult);
        $appData['login'] = true;
    }else{
        $appData['login'] = false;
    }
}else{
    $appData['login'] = false;
}
?>

Sessions are basically temporary data stored on your hosting server for a client connecting to you, it generates a random token, much like the cookie setup above,to validate your session then once you validate the server has access to variables set whilst that user is connected. such as setting $_SESSION['name'] = 'Biiim'; on one page, once i open another page the session token gets passed along and it will remember that var has been set so you can re-use it by doing echo $_SESSION['name'];.

Cookies are data stored on the users computer so say you set $_COOKIE['name'] = 'Biiim'; that data is stored on my browser and i can go in and edit it, it also requires no validation cause its on my pc anyone could create that cookie without your site even creating it, the cookie method above uses a cookie called token which is some large random string, very hard to guess, the script uses that string to validate a user has logged in correctly and has to match the exact token your script created for the user.

I just set a token cookie then store all other data within mysql, that way it doesnt get lost.

Effectively using that method there is little difference but sessions will always be more secure since the data is stored on your server a person could log on to the users computer and browse his stored cookies - not a good idea to store passwords in cookies. If you want to be really secure you need to use ssl(https) which encrypts data requests so your token can't get hijacked(the thing that identifys you), you generally dont need that unless you are transmitting card details or something quite personal/valuble though.

@Biim,Thank you so much for this,okay i will try on this code,but i am confuse i have no token field in my cookie_tble if i will put this token field,and how can i create my register.php on this what value i put in the token field.if the user will register.

Thank you in advance.

here is my register.php

    <?php
      include_once('condb.php');
      $msg='';
      $txtusername = '';
      $password = '';
        if (isset($_POST['REGISTER']))
          {
           $txtusername = $_POST['txtusername'];
           $txtpassword = $_POST['txtpwd'];

           $msg=register($txtusername,$txtpassword);

          } 


    ?>

    <html>
       <title>Register</title>
       <body>
          <h1>Resiter</h1>
          <form method = "post">
            <table border="2">
              <tr>
                <td>UserName:</td>
                <td><input type="text" name="txtusername"></input></td>
              </tr>
              <tr>
                <td>Password:</td>
                <td><input type="text" name="txtpwd"></input></td>
              </tr>
              <tr >
               <td></td>
                <td>
                  <input type="submit" name="REGISTER" value="Register"></input>
                  <input type="reset" value="cancel"></input>
                </td>
              </tr>
          </form>

           <div style="color:red;">
               <?php echo $msg ?>
           </div>
           <a href="login.php">Click here to Login</a>
       </body>

      </html>

===condb.php===

 <?php
   $con = mysql_connect('localhost','root','');
   if(!$con){die('Not connected to server'.mysql_error());}


   mysql_select_db('cookie',$con); 
   function register($username,$password)
    {
      $sql = "INSERT INTO cookie_tbl values(default,'$username','$password')";
      mysql_query($sql);

      if (!$sql)
       return 'not succesfully inserted';
      else  
       return 'succesfully inserted';

      mysql_close();       
    }    
?>

I put default value there for the 'id' auto increment

in my cookie_tbl i have 3 fields,

ID=AUTO INCREMENT
NAME
PASSWORD

@Biim,is it okay to ask to you this,where did you learn this in making the log-in and log-out.

Thank you in advance.

Thank you so much for this,okay i will try on this code,but i am confuse i have no token field in my cookie_tble if i will put this token field,and how can i create my register.php on this what value i put in the token field.if the user will register.

You will need to create a token field in the table, the token doesn't need to entered when they register, just leave it NULL or whatever you like. Once they login the token will be set on their computer and in your database so they will match up. You may also want to make another field with the time the token was created so you can get it to expire after a certain amount of time.

is it okay to ask to you this,where did you learn this in making the log-in and log-out.

From google really, i just google things i want to do and find ways to do them.

I remember i got some simple login example which used a token with a cookie like 3/4 years ago now - was a lot of headaches trying to understand it and get something working.

Now i just understand php a lot better i just looked at your code and edited to give a client a token once hes logged in and quick include page to check the token matches and which user he is logged in as.

@Biim,okay thank you again and i will write it back to you if i have some doubt....

more power to you always.

@Biim,i forgot to ask,

Here Cookies are data stored on the users computer so say you set $_COOKIE['name'] = 'Biiim';that data is stored on my browser and i can go in and edit it"

I looked at in my browser but i could not find the cookie stored.where does the cookie stored.can you help me on this please.

Thank you in advance.

It depends on which browser you use:

I use chrome, on chrome you press ctrl + shift + I Then click on the resources tab, you can see the cookies you have set and can edit/delete them

Firefox, Safari & opera will definitely have a similar thing to edit cookies, maybe its an add on - im not sure about IE though.

@Biim,Thank you for the reply about finding the cookie,i have another question on your code.

what is the purpose of the str_replace and you set the first parameter in single quote,and an empty
in second parameter in $txtusername?why did you put that code there?please enligthen my mind.Thank you in advance.

    <?php 
       if(ISSET($_POST['login'])){
        $txtusername = $_POST['txtusername'];
        $txtusername = str_replace("'",'',$txtusername);
        $txtusername = str_replace('"','',$txtusername);
        $txtpassword = $_POST['txtpassword'];
        $txtpassword = str_replace("'",'',$txtpassword);
        $txtpassword = str_replace('"','',$txtpassword);

str_replace, looks for a character/string within another string and replaces it:

$newstring = str_replace($search_for_this,$replace_it_with_this,$within_this_string);

The reason i did it with that is you are putting the variables into a mysql query, so you want to take out any quotes so a user can't get your query to run something you don't want it to. You should probably take out back slashes too:

<?php 
if(ISSET($_POST['login'])){
$txtusername = $_POST['txtusername'];
$txtusername = str_replace("'",'',$txtusername);
$txtusername = str_replace('"','',$txtusername);
$txtusername = str_replace('\\','/',$txtusername);
$txtpassword = $_POST['txtpassword'];
$txtpassword = str_replace("'",'',$txtpassword);
$txtpassword = str_replace('"','',$txtpassword);
$txtpassword = str_replace('\\','/',$txtpassword);
$sql = "SELECT `user_id` FROM cookie_tbl where name = '$txtusername' and
           password = '$txtpassword'";

I usually just replace them with forward slashes since theres no trouble with them.

Heres your query:
SELECT user_id FROM cookie_tbl where name = '$txtusername' and password = '$txtpassword'

Now imagine $txtpassword was set to "`123' OR 1"

1 will return everything in the table! making him login as the first user in the table, likely to be an admin. If you replace double and single quotes it will prevent any user from doing something like that with the logon, especially watch out for queries that use the update, drop or delete commands.

@Biim, Thank you so much for this...i really appreciated it.more power to you always.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.