How to set cookie in php?

Issue

I have use this code as set the cookie for a begginer level. It’s basic and not much complex code. Easily understandable by begginer.

if(!empty($_POST["remember"])) {
    setcookie ("username",$_POST["username"],time()+ 3600);
    setcookie ("password",$_POST["password"],time()+ 3600);
    echo "Cookies Set Successfuly";
} else {
    setcookie("username","");
    setcookie("password","");
    echo "Cookies Not Set";
}
```

Solution

You need to set your cookie before the header() function,
so:

if(isset($_REQUEST['submit']))
    {
        $email="[email protected]";
        $password="dummy123";
    
        if($_REQUEST['email']==$email && $_REQUEST['password']==$password)
        {
            $_SESSION['email']=$email;
            setcookie("email",$email, time()+3600);
            setcookie("password",$password, time()+3600);
            header("location:index.php");
        }
        else {
            $err="Authentication Failed, Try Again!";
        }
    }
    ?>

but is not a good idea to save a clear password in cookie 🙂 pay attention

Answered By – Mariano

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published