0

I don't know what is going wrong in my code.I have already implemented login and signup using ajax calls. Now, I am trying to implement remember me using cookies in php. My code for that goes like this

<?php require 'database.php';
session_start();
if(!empty($_POST["login"])) {
    #$conn = mysqli_connect("localhost", "root", "", "blog_samples");
    $sql = "Select * from login where Username = '" . $_POST["member_name"] . "' and Password = '" . ($_POST["member_password"]) . "'";
    $result = mysqli_query($conn,$sql);
    $user = mysqli_fetch_array($result);
    if($user) {

            if(!empty($_POST["remember"])) {
                setcookie ("member_login",$_POST["member_name"],time()+ (10 * 365 * 24 * 60 * 60));
                setcookie ("member_password",$_POST["member_password"],time()+ (10 * 365 * 24 * 60 * 60));
            } else {
                if(isset($_COOKIE["member_login"])) {
                    setcookie ("member_login","");
                }
                if(isset($_COOKIE["member_password"])) {
                    setcookie ("member_password","");
                }
            }
            header("location:private.php");
    }
}
?>  


<!DOCTYPE html>
<html >
<body>
  <div class="container-fluid">
 <div class="form-body-login col-md-6 col-xs-6">

   <form class="Login" method="post" action="private.php">
     <div class="row buttons">
       <div type="submit" class="col-md-6 col-xs-6 login">Login</div>
       <div type="submit" class="col-md-6 col-xs-6 sign_up">Sign up</div>
     </div>
     </div>
     <div class="login_body">
       <div class="row user_name">
         <i class="fa fa-user fa-2x col-md-1 col-xs-1" aria-hidden="true"></i>
         <input type="text" class="col-md-10 col-xs-10 username" id="username_login" placeholder="abc@xyz.com" name="member_name" value="<?php if(isset($_COOKIE["member_login"])) { echo $_COOKIE["member_login"]; } ?>" />
       </div>
     <div class="row pwd">
       <i class="fa fa-key fa-2x col-md-1 col-xs-1" aria-hidden="true"></i>
     <input type="password" class="col-md-10 col-xs-10 password" id="password_login" placeholder="Password" name="member_password" value="<?php if(isset($_COOKIE["member_password"])) { echo $_COOKIE["member_password"]; } ?>"/>
     </div>
        <div class="row remember col-md-11 col-xs-11">
        <label><input type="checkbox" name="autologin" id="checkbox" name="remember" <?php if(isset($_COOKIE["member_login"])) { ?> checked <?php } ?>/> Remember Me </label>
        </div>
        <div class="row col-md-11 col-xs-11">
          <button type="submit" id="button" name="login">Login</button>
        </div>
     </div>
     <div class="form-body-signup">
     <div class="row username_signup">
     <input type="text" id="username_signup" class="col-md-10" placeholder="Enter user name"/>
     </div>
       <div class="row password_signup">
         <input type="password" id="password_signup" class="col-md-10 col-xs-10" placeholder="Enter password here" />
       </div>
       <div class="row phone">
         <input type="text" id="phone" class="col-md-10 col-xs-10" placeholder="enter phone number" />
       </div>

     <div class="row signup_button">
       <button type="submit" id="check">Create New User</button>
     </div>
          </div>
   </form>


</div>   
  </div>  

</body>
</html>

On login or signup, after doing all the necessary validations, the page directs to private.php. That page looks something like this:

<?php
echo"Hello";
session_start();
#$_SESSION["member_id"] = "";
session_destroy();
#header("Location: ./");
?>

But somehow, the cookies are not getting stored if I check the remember me check box. I am doing this for the first time and don't really know what is going wrong here.

Aayushi
  • 1,736
  • 1
  • 26
  • 48
  • 1st of all, your code isn't safe : you should **really** consider using [PPS : Prepared Parameterized Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). This will help [Preventing SQL injection](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). And you should not store plain-text password, neither store them in cookie -> refer to `password_hash` -> [password_hash](http://php.net/manual/en/function.password-hash.php) and `password_verify` [password_verify](http://php.net/manual/en/function.password-verify.php) – OldPadawan May 01 '17 at 07:12
  • That I have done in my original code. I have only having issues in the remember functionality. Thanks anyway @OldPadawan – Aayushi May 01 '17 at 07:14
  • plus that you can't access `$_COOKIE["member_login"]` after setting it -> `Cookies will not become visible until the next loading of a page that the cookie should be visible for.` as per the [PHP doc](http://php.net/manual/en/function.setcookie.php) – OldPadawan May 01 '17 at 07:17
  • where do i have to add this member_login? In the form? – Aayushi May 01 '17 at 07:18

2 Answers2

0

set_cookie does not update the $_COOKIE super global array in my experience until after the next page load. So if you're saving information to cookies, remember that you also need to add it manually to $_COOKIE at the same time so you'll need to add:

$_COOKIE['member_login'] = $_POST['member_login'];

For example, if you want to check what the value is for the cookie without reloading the script.

Here's an example of what the code should look like:

if($user) {
    if(!empty($_POST["remember"])) {
        setcookie ("member_login",$_POST["member_name"],time()+ (10 * 365 * 24 * 60 * 60));
        $_COOKIE['member_login'] = $_POST['member_login'];      // This is new
        setcookie ("member_password",$_POST["member_password"],time()+ (10 * 365 * 24 * 60 * 60));
        $_COOKIE['member_password'] = $_POST['member_password'];        // This is new
    } else {
        if(isset($_COOKIE["member_login"])) {
            setcookie ("member_login","");
            $_COOKIE['member_login'] = '';      // This is new
        }
        if(isset($_COOKIE["member_password"])) {
            setcookie ("member_password","");
            $_COOKIE['member_password'] = '';       // This is new
        }
    }
    header("location:private.php");
}

That being said, @OldPadawan has a point that you really should sanitize the data being submitted via the form, or you'll leave yourself open to SQL injection attacks and XSS attacks.

It may also be easier in the future if you wrap both set_cookie and setting the super-global $_COOKIE into a complete function like this:

function set_inline_accessible_cookie( $key, $value, $exp = null ) {
    if ( is_null( $exp ) || ! is_numeric( $exp ) ) {
        $exp = time() + ( 86400 * 30 );
    }
    $_COOKIE[ $key ] = $value;
    return setcookie( $key, $value, $exp, '/' );
}
bdb.jack
  • 147
  • 1
  • 8
0

Cookies will not become visible until the next loading of a page that the cookie should be visible for. according to the PHP doc

For what you want to achieve, (IMHO) best would be :

  • check against DB after you sanitize user's data
  • set (all) cookie(s)
  • redirect to private.php (cookie will be active then)
  • check cookie(s) on that page to grant/refuse access

In your case : $sql -> $result -> $user -> setcookies (all at once) -> redirect. Below a working example (page is self-called -> 'remember-me.php'):

<?php
// only example, adapt to your needs
error_reporting(E_ALL); ini_set('display_errors', 1);
//print_r($_COOKIE); // only for checking if needed

if(isset($_POST['login'])) {

$member_name = $_POST['member_name'];
$remember_me = $_POST['remember_me'];

//print_r($_POST); // only for checking if needed

if(isset($remember_me)) {

setcookie("member_login", $member_name);
setcookie("remember_me", 1);

echo"We will remember you next time! <a href=\"remember-me.php\">Check this !</a>"; // or redirect to private.php without output before

 }
}

?>
<form method="post" action="remember-me.php">
    <p><input type="text" id="member_name" name="member_name" value="<?php if(isset($_COOKIE["member_login"])) { echo $_COOKIE["member_login"]; } ?>" /></p>
    <p><input type="checkbox" name="remember_me" id="remember_me" name="remember_me" <?php if(isset($_COOKIE["remember_me"])) { ?> checked="checked" <?php } ?>/> Remember Me </label></p>
    <p><input type="submit" id="login" name="login" value="Login" /></p>
</form>

EDIT 2 -> to adapt to your initial question (after chat and further inquiry - below is raw code example) :

<?php
session_start();
require'database.php';

if(isset($_POST['login'])) {
// connect to DB
$sql = " xxxx "; // make query
if($user) { // if results

    $member_name = $_POST['member_name']; // or return from DB row, up to you
    $remember_me = $_POST['remember_me'];

    if(isset($remember_me)) {

    setcookie("member_login", $member_name);
    setcookie("remember_me", 1);
    }
    // could use session here if needed and no output before
    header("location:private.php");
   }
  }
?>

NOT ONLY on one page, but on all of them (including the one you show), you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection

and also :

never ever use/store plain-text password, use password_hash and password_verify

Community
  • 1
  • 1
OldPadawan
  • 1,247
  • 3
  • 16
  • 25
  • I added a `In your case` line in answer – OldPadawan May 01 '17 at 07:30
  • as far as I understand, the redirection is done using header location in cookies.Am i right? @OldPadawan – Aayushi May 01 '17 at 07:32
  • as you won't be able to check cookie values on the same page, you set it/them and redirect immediately yes (EDIT: make sure no output before or you'll get warned !) – OldPadawan May 01 '17 at 07:33
  • so,in my case I have already directed them to private.php. In that php page, if I do header("Location: ./"), then my login signup buttons stop working, so I commented that line. But of no use for remember me. – Aayushi May 01 '17 at 07:36
  • when user want to log in, don't you ask for `login + pwd + remember me` ? if not, should be done at same time though -> if access granted, cookies are set and redirect, if not -> error – OldPadawan May 01 '17 at 07:39
  • if i do this, and refresh the page, then also the input fields are not getting populated with the values.Why is this happening? @OldPadawan – Aayushi May 01 '17 at 08:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/143076/discussion-between-oldpadawan-and-aayushi). – OldPadawan May 01 '17 at 08:27