i create some login form and i put remember me check box below username and password field
this is my login form code :

<?php error_reporting(0); include "../db.php"; ?>
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=us-ascii" />
    <title>IN ADMIN PANEL | Powered by Mahdi Yazdani</title>
    <link rel="shortcut icon" href="images/loginpage.ico" mce_href="images/loginpage.ico" />
<!-- Copyright C 2012-Feb  Mahdi Yazdani  2010-2012 -->  
    <link type="text/css" href="./style.css" rel="stylesheet" />
    <link type="text/css" href="./css/login.css" rel="stylesheet" />

    <script type='text/javascript' src='./js/jquery-1.4.2.min.js'></script>   <!-- jquery library -->
    <script type='text/javascript' src='./js/iphone-style-checkboxes.js'></script> <!-- iphone like checkboxes -->

    <script type='text/javascript'>
        jQuery(document).ready(function() {
            jQuery('.iphone').iphoneStyle();
        });
    </script>

    <!--[if IE 8]>
        <script type='text/javascript' src='http://hello.amnesio.com/js/excanvas.js'></script>
        <link rel="stylesheet" href="http://hello.amnesio.com/css/loginIEfix.css" type="text/css" media="screen" />
    <![endif]--> 

    <!--[if IE 7]>
        <script type='text/javascript' src='http://hello.amnesio.com/js/excanvas.js'></script>
        <link rel="stylesheet" href="http://hello.amnesio.com/css/loginIEfix.css" type="text/css" media="screen" />
    <![endif]--> 

<meta charset="UTF-8"></head>
<body>
<div id="background">
<div id="container">
          <div id="logo">
                <img src="./assets/logologin.png" alt="Logo" />
            <br>
                             <span style="font-size:13px; color:#FFF; font-style:italic;"><?php
    $error=@$_REQUEST['e']; if($error=="error")
    {   echo "<img src=\"images/error.png\" border=\"0\" />";
    echo "<b>"." Invalid username or password."."</b>"; } ?></span>
  </div>
            <div id="box"> 
                <form action="main.php" method="POST"> 
                    <div class="one_half">
                        <p><input name="username" value="username" class="field" onblur="if (jQuery(this).val() == &quot;&quot;) { jQuery(this).val(&quot;username&quot;); }" onclick="jQuery(this).val(&quot;&quot;);" test autocomplete="off" /></p>
                        <p><input type="checkbox" class="iphone" /><label class="fix">Remember me</label></p> 
                    </div>
                    <div class="one_half last">
                        <p><input type="password" name="password" test autocomplete="off" value="asdf1234" class="field" onblur="if (jQuery(this).val() == &quot;&quot;) { jQuery(this).val(&quot;asdf1234&quot;); }" onclick="jQuery(this).val(&quot;&quot;);" />    </p>
                        <p><input type="submit" value="Login" class="login" /></p>
                    </div>
            </form> 
        </div> 

        </div>
    </div>
<!-- Copyright C 2012-Feb  Mahdi Yazdani  2010-2012 -->    
</body>
</html>

and then with using php i can truly login and so on but the problem is here i want to use remember me check box i heard some things about using cookie but actually i dont know about that please help me with this problem !
here it is my login page :
`

<?php
ob_start();
session_start();
error_reporting(0);
include "../db.php";

$username=$_POST['username'];

$password=md5($_POST['password']);

$sql=mysql_query("select * from admin where user='$username' and pass='$password' "); $c=mysql_num_rows($sql);

if($c==1)
{
$_SESSION['user']=$username;
 header("location:popular/learn/");}

else{ header("location:index.php?e=error"); }
ob_end_flush();
?>

`

Cookies are accessed using the $_COOKIE superglobal and work VERY similar to $_SESSION. The important thing will be to make sure the content of the cookie can't be easily hacked by an intruder since cookies are stored on the browser's computer.

first the form input needs to be right:

<input type="checkbox" class="iphone" /><label class="fix">Remember me</label></p>
should be something like:

<input type="checkbox" name="rememberme" class="iphone" value="yes"/><label class="fix">Remember me</label></p> 

Then login script to set the cookie:

<?php
ob_start();
session_start();
error_reporting(0);
include "../db.php";
$username=$_POST['username'];
$password=md5($_POST['password']);
$sql=mysql_query("select * from admin where user='$username' and pass='$password' ");
$c=mysql_num_rows($sql);
if($c==1){
    $mysqlData = mysql_fetch_assoc($sql);//fetch data from mysql query
    $_SESSION['user']=$username;

    $token = md5(rand());//generate a random token
    //set an expire time
    if($_POST['rememberme'] == 'yes'){
        $expire = time()+(60*60*24*14);//(time() = time now in seconds + seconds*minutes*hours*days) ie. 14 days from now in seconds
    }else{
        $expire = time()+(60*30);//30 mins
    }
    $expiresdate = date("Y-m-d H:i:s",$expire);//get expire datetime in mysql format
    $now = date("Y-m-d H:i:s");//time now
    $setTokenQuery = "UPDATE `admin` SET `token` = '$token',`tokendate` = '{$now}',`tokenexpires` = '{$expiresdate}' WHERE `adminid` = {$mysqlData['adminid']}";
    //update the database to tell it he has logged in and this is the token he can resume his session with - until it expires
    if(mysql_query($setTokenQuery)){
        //token updated successful
    }else{
        //error
        die("Error at token update: ".mysql_error());
    }
    setcookie("token", $token, $expire, "/");//the actual function to set a cookie
    //var_dump($mysqlData);//if you want to see what data it has
    header("location:popular/learn/");
}else{
    header("location:index.php?e=error");
}
ob_end_flush();
?>

Then on your central site file (if you have one) you will need to validate he is logged in.

Save this file as app.php and tell other pages to require it require_once(app.php); then you'll have access on them pages to an array called $userdata which has $userdata['login'] set as a bool true or false.

If the page requires a login set $adminarea = true; just before the require_once and it will redirect to login if they arn't logged in

if(ISSET($adminarea) && $adminarea){//does the page require log in?
    if(!ISSET($_COOKIE['token']) || !ctype_alnum($_COOKIE['token'])){//no cookie or invalid go to login
        header('Location: '.DIR_ROOT.'login.php');
    }else{
        $cookie = $_COOKIE['token'];//safe from the ctype_alnum above
        $Q = "SELECT * FROM `admin` WHERE `token` = '{$cookie}' AND `tokenexpires` > '".date("Y-m-d H:i:s")."' LIMIT 1";
        $R = mysql_query($Q);
        if($R !== false){//user found, pull user data and set login to true
            $userdata = mysql_fetch_assoc($R);
            $userdata['login'] = true;
        }else{//failed, go to login
            header('Location: '.DIR_ROOT.'login.php');
            $userdata['login'] = false;
        }
    }   
}else{//login not required
    if(!ISSET($_COOKIE['token']) || !ctype_alnum($_COOKIE['token'])){//no cookie or invalid go to login
        $userdata['login'] = false;
    }else{
        $cookie = $_COOKIE['token'];//safe from the ctype_alnum above
        $Q = "SELECT * FROM `admin` WHERE `token` = '{$cookie}' AND `tokenexpires` > '".date("Y-m-d H:i:s")."' LIMIT 1";
        $R = mysql_query($Q);
        if($R !== false){//user found, pull user data and set login to true
            $userdata = mysql_fetch_assoc($R);
            $userdata['login'] = true;
        }else{//failed
            $userdata['login'] = false;
        }
    }
}

Also the admin mysql table will need 3 more fields:
"token" varchar(64)
"tokendate" datetime
"tokenexpires" datetime

And thats generally how i set up a site.

Edit: Like madcoder says, cookies are more vunerable than sessions so avoid storing anything personal in them - to make it more secure you could store the users ip as well and check that matches.

commented: Good +0

Error at token update: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

i got this !!! why ?

if(mysql_query($setTokenQuery)){
        //token updated successful    //where is the code here ???
    }else{
        //error
        die("Error at token update: ".mysql_error());
    }

is it necessary to require app.php page in each page of website ?
if so please explain more i didn't get notice !
What is it doing exactly ? should i include or require it in each page ?

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.