Thomas
Thomas

Reputation: 5089

PHP setcookie issue

After a user signs in and his password is verified, I need to store his username in a cookie. I tried to simply add setcookie() when the password is successfully verified in the section that looks like if ( $password_match == $user_login_password ) {... but for some reason it doesn't seem to be working. I can't set cookies when a user successfully logins with correct password/username. Is there some reason you can't setcookies from inside a function?

    public function write($p) {

    if ( $_POST['user_login_username'] )
      $user_login_username = mysql_real_escape_string($_POST['user_login_username']);

    if ( $_POST['user_login_password'] )
      $password = mysql_real_escape_string($_POST['user_login_password']);
      $password .= 'some_Salt';
      $user_login_password = hash('sha256', $password);
    } elseif ( $user_login_username && $user_login_password ) {
        $q = "SELECT * FROM users WHERE username = '$user_login_username'";
        $r = mysql_query($q);

        if ( $r !== false && mysql_num_rows($r) > 0 ) {
            while ( $a = mysql_fetch_assoc($r) ) {
            $password_match = stripslashes($a['password']);
            }

            if ( $password_match == $user_login_password ) {

                echo $this ->display_login('Correct!');

                setcookie('user','some_username');

            } else {
                echo $this ->display_login('Wrong Password!');
            }

        } else {
            echo $this ->display_login('That username does not exist.');
        }



      return;

     } else {
      return false;
    }
  }

Upvotes: 0

Views: 634

Answers (2)

Thomas
Thomas

Reputation: 5089

Ahh I got it. Protocol restriction with setcookie, I was trying to set it after the tags. Thanks to everyone who looked, I should have read the documentation better. Sorry!

Upvotes: 0

user798596
user798596

Reputation:

I'd do this that way:

function mysetcookie($name, $value, $timestamp=null, $directory='/') {
    return setcookie($name, $value, time()+$timestamp, $directory);
}

And I'd be using mysetcookie() instead of setcookie() :) And I'd consider reading this:

http://php.net/manual/en/function.setcookie.php

Upvotes: 1

Related Questions