user3728517
user3728517

Reputation: 157

php cookies are not working

This is my login script but problem is that cookies not working i mean cookies are not set on the user computer my code is:

<!doctype html>
<html>
<head>
<title>Login</title>

</head>
<body>

<p><a href="register.php">Register</a> | <a href="login.php">Login</a></p>
<h3>Login Form</h3>
<form action="" method="POST">
Email: <input type="text" name="ename"><br />
Password: <input type="password" name="pass"><br /> 
<input type="submit" value="Login" name="submit"><br />
</form>
</body>
</html>

This is php code i mean getting values from html form and insert in to database

<?php

include'connect.php';

if(isset($_POST["submit"])){

    if(!empty($_POST['ename']) && !empty($_POST['pass']))
    {
        $user=$_POST['ename'];
        $pass=$_POST['pass'];
        $securepass=md5($pass);
        $query=mysql_query("SELECT * FROM users WHERE user_email='".$user."' AND user_pass='".$securepass."'");
        $numrows=mysql_num_rows($query);
        if($numrows!=0)
        {
            while($row=mysql_fetch_assoc($query))
            {
                $dbemail=$row['user_email'];
                $dbpassword=$row['user_pass'];
                $dbuser=$row['user_name'];
            }

            if($user == $dbemail && $securepass == $dbpassword)
            {
                setcookie('gyanuser',$dbuser,$dbemail,$dbpassword,mktime()+84600,'/') or die("cookies can not be set");
                /* Redirect browser */
                header("Location: member.php");
            }
        }
        else 
        {
            echo "Invalid username or password!";
        }
    } else {
        echo "All fields are required!";
    }
}
?>

if i use session it working fine but can not set cookies thats the problem i face when i hit submit then it should cookies can not be set .

Upvotes: 0

Views: 65

Answers (1)

Satish Sharma
Satish Sharma

Reputation: 9635

you have to set three different cookie for each value like this

setcookie('gyanuser',$dbuser,mktime()+84600,'/') or die("cookies can not be set");
setcookie('gyanemail',$dbemail,mktime()+84600,'/') or die("cookies can not be set");
setcookie('gyanpassword',$dbpassword,mktime()+84600,'/') or die("cookies can not be set");

Now you can access these cookies by using

$_COOKIE['gyanuser']
$_COOKIE['gyanemail']
$_COOKIE['gyanpassword']

UPDATE 2 :

if you want to save all variables data in one cookie with a separator like , use this

$cookie_value = "'".$dbuser.",".$dbemail.",".$dbpassword."'";

setcookie('gyanuser',$cookie_value,mktime()+84600,'/') or die("cookies can not be set");

Upvotes: 2

Related Questions