I need login with cookies to hide comment form, from user who are not logged in.
Users can view article without login but can not comment without login

Database

CREATE TABLE IF NOT EXISTS `members` (
  `id` bigint(12) NOT NULL AUTO_INCREMENT,
  `fname` varchar(500) NOT NULL,
  `lname` varchar(500) NOT NULL,
  `email` varchar(250) NOT NULL,
  `username` varchar(250) NOT NULL,
  `pass` varchar(250) NOT NULL,
  PRIMARY KEY (`id`,`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `articles` (
  `id` bigint(12) NOT NULL AUTO_INCREMENT,
  `userid` varchar(12) NOT NULL,
  `catid` varchar(12) NOT NULL,
  `title` varchar(500) NOT NULL,
  `content` longtext NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

article.php

<?php 
    include('config.php');

    $query="SELECT * FROM articles";
    $result = mysql_query($query);
    while($row = mysql_fetch_assoc($result)) 
    { 
        $title=$row["title"];
        $content=$row["content"];

        echo "$title"; 
        echo "$content"; 
?>

<div id="addCommentContainer">
    <p>Add a Comment</p>
    <form id="addCommentForm" method="post" action="comment.php">
        <div>                
            <input type="hidden" name="userid" id="id" />
            <input type="hidden" name="articleid" id="id" /> 

            <textarea name="body" id="body" cols="20" rows="5"></textarea>

        <input type="submit" id="submit" value="Submit" />
        </div>
    </form>
</div>
<?php 
    } 
?>

What are you having problems with?

Don't know if your login is going to be public but for a public account creating site you want to hash the passwords so they arn't stored in a database and there's no reason you can't use hash for private uses.

CREATE TABLE `users` (
  `uid` int(5) NOT NULL AUTO_INCREMENT,
  `title` varchar(30) DEFAULT NULL,
  `fname` varchar(15) DEFAULT NULL,
  `sname` varchar(15) DEFAULT NULL,
  `email` varchar(60) DEFAULT NULL,
  `hash` varchar(64) DEFAULT NULL,
  `salt` varchar(64) DEFAULT NULL,
  `tokendate` datetime DEFAULT NULL,
  `tokenexpires` datetime DEFAULT NULL,
  `token` varchar(64) DEFAULT NULL,
  `cat` int(3) DEFAULT NULL,
  `busname` varchar(60) DEFAULT NULL,
  `busdesc` varchar(200) DEFAULT NULL,
  `tel` varchar(20) DEFAULT NULL,
  `addr1` varchar(40) DEFAULT NULL,
  `addr2` varchar(40) DEFAULT NULL,
  `town` varchar(40) DEFAULT NULL,
  `county` int(3) DEFAULT NULL,
  `postcode` varchar(9) DEFAULT NULL,
  `dbloptin` varchar(50) DEFAULT NULL,
  `dbloptindate` datetime DEFAULT NULL,
  `newsletter` tinyint(1) NOT NULL DEFAULT '0',
  `advertiser` int(1) DEFAULT NULL,
  `lastip` varchar(16) DEFAULT NULL,
  `reset` smallint(1) NOT NULL DEFAULT '0',
  `imported` smallint(1) DEFAULT '0',
  `deleted` smallint(1) DEFAULT '0',
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=314 DEFAULT CHARSET=latin1

Then heres some functions i use for doing a login:

<?php
function randStr($len = 6){
    if(is_int($len) && $len > 0){
        $string = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',$len)),0,$len);
    }else{
        $string = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',6)),0,6);
    }
    return $string;
}

function hashPass($pass,$salt){
    $len = strlen($pass);
    //$p1 = substr($pass,0,floor($len));//get creative with some hashing
    $p1 = $pass;
    $hash = hash('sha256', $salt . $p1);
    return $hash;
}
function noQuotes($str){
    $str = str_replace('"', '', $str);
    $str = str_replace("'", '', $str);
    $str = str_replace("\\", '', $str);
    return $str;
}
function makeNewUser($DB,$email,$pass,$activationcode,$extra){
    $salt = randStr(6);
    $hash = hashPass($pass, $salt);
    $Q = "INSERT INTO `users` (`title`,`fname`,`sname`,`email`,`hash`,`salt`,`cat`,"
        ."`busname`,`busdesc`,`tel`,`addr1`,`addr2`,`town`,"
        ."`county`,`postcode`,`dbloptin`,`advertiser`,`newsletter`,`lastip`)"
        ." VALUES('{$extra['title']}','{$extra['fname']}','{$extra['sname']}','{$email}','{$hash}','{$salt}','{$extra['catid']}',"
        ."'{$extra['busname']}','{$extra['busdesc']}','{$extra['telephone']}','{$extra['house']}','{$extra['street']}','{$extra['town']}',"
        ."'{$extra['county']}','{$extra['postcode']}','{$activationcode}','{$extra['advertisertoggle']}','{$extra['newsletter']}','".noQuotes($_SERVER['REMOTE_ADDR'])."')";
    $R = mysqli_query($DB, $Q);
    if($R !== false){
        $IID = mysqli_insert_id($DB);
    }else{
        $IID = false;
    }
    return $IID;
}
// DEFINED QUERY - update IP
$D = "UPDATE users SET lastip = '".$ipaddress."' WHERE email in ('".$user."') ";
//$DB = mysqli_connect(...);
$A = "SELECT * FROM `users` WHERE `email` = '".$user."' ";
$B = mysqli_query($A,$DB) or die(mysqli_error($DB));
if (mysqli_num_rows($B) > 0){
    // check if password is correct
    while ($C = mysqli_fetch_assoc($B)){
        $hash = hashPass($password, $C['salt']);
        // CORRECT
        if ($hash == $C['hash']) {
            // update IP address for user
            $E = mysqli_query($D,$DB) or die(mysqli_error($DB));

            // set and deliver cookie
            if(isset($_POST['rememberme']) && $_POST['rememberme'] == 'true'){
                $expire = time()+(60*60*24*14);
            }else{
                $expire = time()+1800;
            }
            $expiresdate = date("Y-m-d H:i:s",$expire);

            function makeNewToken($DB){
                $token = md5(rand());
                $Q = "SELECT `token` FROM `users` WHERE `token` = '{$token}'";
                $R = mysqli_query($Q);
                if($R !== false && mysqli_num_rows($R) > 0){
                    $token = false;
                }
                return $token;
            }

            $token = false;
            while($token === false){
                $token = makeNewToken($DB);
                if($token !== false){
                    break;
                }
            }
            $now = date("Y-m-d H:i:s");

            $updtoken = "UPDATE `users` SET `token` = '$token',`tokendate` = '{$now}',`tokenexpires` = '{$expiresdate}' WHERE email in ('".$user."')";
            mysqli_query($updtoken) or die("Login Error"); 
            setcookie("token", $token, $expire, "/");

            // Check if this is a password reset
            if ($C['reset'] == "1") {
                //echo "<!-- This is a password reset -->";
                header("Location:./forcereset.php");
                exit;
            }

            // go to account admin page
            header("Location: ./accountadmin.php");
        }else{// go back to login page
            header("Location: ./login.php");
        }
    }
}else{
    //go back to login page
    header("Location: ./login.php");
} 
?>

Note the

$updtoken = "UPDATE `users` SET `token` = '$token',`tokendate` = '{$now}',`tokenexpires` = '{$expiresdate}' WHERE email in ('".$user."')";
            mysqli_query($updtoken) or die("Login Error"); 
            setcookie("token", $token, $expire, "/");

Then on the rest of the site I include a file called app.php, which contains:

app.php
<?php
//require_once 'config.php';
//config contents
define("DIR_DOMAIN",'example.com');
define("DIR_ROOT",'http://www.example.com/');
define("SITE_NAME",'my site');
define("DB_HOST",'ipaddress');
define("DB_USER",'user');
define("DB_PASS",'pass');
define("DB_DB",'dbname');

//require_once 'site_func.php';
function dbFetchAssoc($R){
    $D = array();
    $i = 0;
    while($row = mysqli_fetch_assoc($R)){
        $D[] = $row;
        $i++;
    }
    return $D;
}
//$DB = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_DB);
$A = array();
if(ISSET($adminarea) && $adminarea){
    if(!ISSET($_COOKIE['token'])){
        header('Location: '.DIR_ROOT.'login.php');
    }else{
        $cookie = noQuotes($_COOKIE['token']);
        $Q = "SELECT * FROM `users` WHERE `token` = '{$cookie}' AND `tokenexpires` > '".date("Y-m-d H:i:s")."' LIMIT 1";
        $R = mysqli_connect($DB, $Q);
        if($R !== false){
            $A = dbFetchAssoc($R);
            $A = $A[0];
            $A['login'] = true;
            $A['DB'] = $DB;
        }else{
            header('Location: '.DIR_ROOT.'login.php');
            $A['login'] = false;
            $A['DB'] = $DB;
        }
    }   
}else{
    if(!ISSET($_COOKIE['token'])){
        $A['login'] = false;
        $A['DB'] = $DB;
    }else{
        $cookie = noQuotes($_COOKIE['token']);
        $Q = "SELECT * FROM `users` WHERE `token` = '{$cookie}' AND `tokenexpires` > '".date("Y-m-d H:i:s")."' LIMIT 1";
        $R = mysqli_connect($DB, $Q);
        if($R !== false){
            $A = dbFetchAssoc($R);
            $A = $A[0];
            $A['login'] = true;
            $A['DB'] = $DB;
        }else{
            $A['login'] = false;
            $A['DB'] = $DB;
        }
    }
}
?>

Following all that, you'll have an array declared as $A with the entry $A['login'] = true if he is logged in and false if he isn't so you can make things appear for logged in users and hidden for people who arn't eg. if($A['login']){echo commentBox();}

@pritaeas

How to create login by setting cookies so that user can be treated as Guest if not logged in. Guest can read article but can not comment. Only logged in users can comment on article .

login from TABLE members using username

I have problem with cookies. Simple code needed. I didn't understood above code

pfft, leaving in 5 minutes so can't write out a simpler one.

basically the important bits is:

This is just a function to make a random string easily:

function randStr($len = 6){
    if(is_int($len) && $len > 0){
        $string = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',$len)),0,$len);
    }else{
        $string = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',6)),0,6);
    }
    return $string;
}

This sets the cookie:

setcookie("token", randStr(20), $expire, "/");

On the next page the cookie will be available as$_COOKIE['token'];

but of course you need something to compare it to so you have to write the token into the database as well hence:

$updtoken = "UPDATE `users` SET `token` = '$token',`tokendate` = '{$now}',`tokenexpires` = '{$expiresdate}' WHERE email in ('".$user."')";

so then you do a select on the table for the $_COOKIE['token'] and if theres a match he's logged in

The above is complex but functions basically do a lot of stuff in one line so you dont have to keep writing it out on every page - its best to understand it all if you use it or bad things happen

randStr(x) takes a number and gives back a random string x characters long based on what you put into it

Need Simple login with cookies please...
I want to hide comment forms only

I use SESSION so I think its the same,
when user logged in set varible $_SESSION['log'] = true;
and check for this variable

if ($_SESSION['log'])  {
// show comment
} else {
// don't show comment button , login to comment
}

@OsaMasw
Thanks

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.