php easy login system fail
<h2>Updates:</h2>

<ul>
<li>9th Apr:</li>
</ul>

<p>I have checked where the problem is. </p>

<p>First of all i added an echo in process_login.php and I deleted the header('location...protected_page.php). The login function (in functions.php) does his job, and writes CORRECTLY: <code>$_SESSION['user_id']</code> as well as <code>$_SESSION['username']</code> and  <code>$_SESSION['login_string']</code>. </p>

<p>Then I deleted the echos in process_login.php and rewrote the header('location.. to protected_page.php.(i back to the original code). And after that added some echos in login_check <strong>before any if</strong> <code>function login_check($mysqli) {
    echo "&lt;br&gt;userid:".$_SESSION['user_id'];
    echo "&lt;br&gt;username:".$_SESSION['username'];
    echo "&lt;br&gt;loginstring:".$_SESSION['login_string'];</code></p>

<p>The result is blank, <strong>so the SESSION variables are wroten correctly in function login but after the header to protected_page the variables seem to be deleted.</strong> Maybe sec_session_start() function is not working well? Anyway i will follow @Manikiran 's advices and I will continue working, removing encryptions or something.... Thank you @Manikiran and @lps</p>

<h2>Original questions:</h2>

<p>I am trying to do a basic login system. However, what i've done doesn't work. The system is basically an index.php where you put your credentials, then the php verifies if your user exists and if the password is correct. Then the user is redirected to protected_page.php. Okay, the authentication part works fine, when the user and password is correct the web page redirects you to protected_page.php and when the user and password is not correct, the page tells you so. </p>

<p>Now, <strong>the problem:</strong> in protected_page.php there is obviously a session "checker", i mean if you connected correctly with your user and password, the page will show you private html information, if you're not connected the page shouldn't show you anything. This is what doesn't works, despite you connect correctly with a user, the page tells you you're not logged in....
<em>(note: the index.php also contains protected html which doesn't work neither)</em></p>

<p><strong>The code:</strong>
<em>(note:sec_session_starts() is suposed to be a way to prevent session hijacking and it contains of course session_start())</em></p>

<p><strong>index.php:</strong> <em>(i guess it works fine, as it redirects to protected_page() when it has to do it. <strong>Maybe the problem is the login(...) function in the part where I set the session data...</strong>).</em></p>

<pre><code> &lt;?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();

if (login_check($mysqli) == true) {
    $logged = 'in';
} else {
    $logged = 'out';
}
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Secure Login: Log In&lt;/title&gt;

        &lt;script type="text/JavaScript" src="js/sha512.js"&gt;&lt;/script&gt; 
        &lt;script type="text/JavaScript" src="js/forms.js"&gt;&lt;/script&gt; 
    &lt;/head&gt;
    &lt;body&gt;
        &lt;?php
        if (isset($_GET['error'])) {
            echo '&lt;p class="error"&gt;Error Logging In!&lt;/p&gt;';
        }
        ?&gt; 
        &lt;form action="includes/process_login.php" method="post" name="login_form"&gt;                      
            Email: &lt;input type="text" name="email" /&gt;
            Password: &lt;input type="password" 
                             name="password" 
                             id="password"/&gt;
            &lt;input type="button" 
                   value="Login" 
                   onclick="formhash(this.form, this.form.password);" /&gt; 
        &lt;/form&gt;

&lt;?php
        if (login_check($mysqli) == true) {
                        echo '&lt;p&gt;Currently logged ' . $logged . ' as ' . htmlentities($_SESSION['username']) . '.&lt;/p&gt;';

            echo '&lt;p&gt;Do you want to change user? &lt;a href="includes/logout.php"&gt;Log out&lt;/a&gt;.&lt;/p&gt;';
        } else {
                        echo '&lt;p&gt;Currently logged ' . $logged . '.&lt;/p&gt;';
                        echo "&lt;p&gt;If you don't have a login, please &lt;a href='register.php'&gt;register&lt;/a&gt;&lt;/p&gt;";
                }
?&gt;      
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p><strong>process_login.php</strong> <em>(works fine i guess)</em></p>

<pre><code>&lt;?php
include_once 'db_connect.php';
include_once 'functions.php';

sec_session_start(); // Our custom secure way of starting a PHP session.

if (isset($_POST['email'], $_POST['p'])) {
    $email = $_POST['email'];
    $password = $_POST['p']; // The hashed password.

    if (login($email, $password, $mysqli) == true) {
        // Login success 
        header('Location: ../protected_page.php');
    } else {
        // Login failed 
        header('Location: ../index.php?error=1');
    }
} else {
    // The correct POST variables were not sent to this page. 
    echo 'Invalid Request';
}
</code></pre>

<p><strong>functions.php:</strong></p>

<pre><code>&lt;?php
include_once 'psl-config.php';
require_once 'passwordLib.php';


function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name
    $secure = true;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);
    // Sets the session name to the one set above.
    session_name($session_name);
    session_start();            // Start the PHP session 
    session_regenerate_id(true);    // regenerated the session, delete the old one. 
}


function login($email, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli-&gt;prepare("SELECT id, username, password 
        FROM members
       WHERE email = ?
        LIMIT 1")) {
        $stmt-&gt;bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt-&gt;execute();    // Execute the prepared query.
        $stmt-&gt;store_result();

        // get variables from result.
        $stmt-&gt;bind_result($user_id, $username, $db_password);
        $stmt-&gt;fetch();

        if ($stmt-&gt;num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts 

            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted. We are using
                // the password_verify function to avoid timing attacks.
                if (password_verify($password, $db_password)) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                "", 
                                                                $username);
                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512', 
                              $db_password . $user_browser);
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    $mysqli-&gt;query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', '$now')");
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}

function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time 
    $now = time();

    // All login attempts are counted from the past 2 hours. 
    $valid_attempts = $now - (2 * 60 * 60);

    if ($stmt = $mysqli-&gt;prepare("SELECT time 
                             FROM login_attempts 
                             WHERE user_id = ? 
                            AND time &gt; '$valid_attempts'")) {
        $stmt-&gt;bind_param('i', $user_id);

        // Execute the prepared query. 
        $stmt-&gt;execute();
        $stmt-&gt;store_result();

        // If there have been more than 5 failed logins 
        if ($stmt-&gt;num_rows &gt; 5) {
            return true;
        } else {
            return false;
        }
    }
}

function login_check($mysqli) {
    // Check if all session variables are set 
    if (isset($_SESSION['user_id'], 
                        $_SESSION['username'], 
                        $_SESSION['login_string'])) {

        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli-&gt;prepare("SELECT password 
                                      FROM members 
                                      WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter. 
            $stmt-&gt;bind_param('i', $user_id);
            $stmt-&gt;execute();   // Execute the prepared query.
            $stmt-&gt;store_result();

            if ($stmt-&gt;num_rows == 1) {
                // If the user exists get variables from result.
                $stmt-&gt;bind_result($password);
                $stmt-&gt;fetch();
                $login_check = hash('sha512', $password . $user_browser);

                if (hash_equals($login_check, $login_string) ){
                    // Logged In!!!! 
                    return true;
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    } else {
        // Not logged in 
        return false;
    }
}

function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&amp;;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&amp;amp;', '&amp;#038;', $url);
    $url = str_replace("'", '&amp;#039;', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}
</code></pre>

<p><strong>protected_page.php: (or maybe the problem is at login_check where it chekcs the session data</strong></p>

<pre><code>&lt;?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();

?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="UTF-8"&gt;
        &lt;title&gt;Secure Login: Protected Page&lt;/title&gt;
        &lt;link rel="stylesheet" href="styles/main.css" /&gt;
    &lt;/head&gt;
    &lt;body&gt;

        &lt;?php if (login_check($mysqli) == true) : ?&gt;
            &lt;p&gt;Welcome &lt;?php echo htmlentities($_SESSION['username']); ?&gt;!&lt;/p&gt;
            &lt;p&gt;
                This is an example protected page.  To access this page, users
                must be logged in.  At some stage, we'll also check the role of
                the user, so pages will be able to determine the type of user
                authorised to access the page.
            &lt;/p&gt;
            &lt;p&gt;Return to &lt;a href="index.php"&gt;login page&lt;/a&gt;&lt;/p&gt;
        &lt;?php else : ?&gt;
            &lt;p&gt;
                &lt;span class="error"&gt;You are not authorized to access this page.&lt;/span&gt; Please &lt;a href="index.php"&gt;login&lt;/a&gt;.
            &lt;/p&gt;
        &lt;?php endif; ?&gt;
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>psl-config and db_connect connects with the db and it's working fine i think. passwordLib.php is a library as my server has php 5.4 and i am using php 5 functions. This library is suposed to help with some passwords encryptions or whatever and i think <strong>the problem is not here neither</strong>. Anyway I put the code:</p>

<pre><code>&lt;?php
/**
 * PHP 5.5-like password hashing functions
 *
 * Provides a password_hash() and password_verify() function as appeared in PHP 5.5.0
 * 
 * See: http://php.net/password_hash and http://php.net/password_verify
 * 
 * @link https://github.com/Antnee/phpPasswordHashingLib
 */

require_once('passwordLibClass.php');

if (!function_exists('password_hash')){
    function password_hash($password, $algo=PASSWORD_DEFAULT, $options=array()){
        $crypt = NEW Antnee\PhpPasswordLib\PhpPasswordLib;
        $crypt-&gt;setAlgorithm($algo);

        $debug  = isset($options['debug'])
                ? $options['debug']
                : NULL;

        $password = $crypt-&gt;generateCryptPassword($password, $options, $debug);

        return $password;
    }
}

if (!function_exists('password_verify')){
    function password_verify($password, $hash){
        return (crypt($password, $hash) === $hash);
    }
}

if (!function_exists('password_needs_rehash')){
    function password_needs_rehash($hash, $algo, $options=array()){
        $crypt = NEW Antnee\PhpPasswordLib\PhpPasswordLib;
        return !$crypt-&gt;verifyCryptSetting($hash, $algo, $options);
    }
}

if (!function_exists('password_get_info')){
    function password_get_info($hash){
        $crypt = NEW Antnee\PhpPasswordLib\PhpPasswordLib;
        return $crypt-&gt;getInfo($hash);
    }
}
</code></pre>

<p>passwordlibclass.php:</p>

<pre><code>&lt;?php
/**
 * PHP 5.5-like password hashing functions
 *
 * Provides a password_hash() and password_verify() function as appeared in PHP 5.5.0
 * 
 * See: http://php.net/password_hash and http://php.net/password_verify
 * 
 * @link https://github.com/Antnee/phpPasswordHashingLib
 */


namespace Antnee\PhpPasswordLib;

if (!defined('PASSWORD_BCRYPT')) define('PASSWORD_BCRYPT', 1);

// Note that SHA hashes are not implemented in password_hash() or password_verify() in PHP 5.5
// and are not recommended for use. Recommend only the default BCrypt option
if (!defined('PASSWORD_SHA256')) define('PASSWORD_SHA256', -1);
if (!defined('PASSWORD_SHA512')) define('PASSWORD_SHA512', -2);

if (!defined('PASSWORD_DEFAULT')) define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);

class PhpPasswordLib{

    CONST BLOWFISH_CHAR_RANGE = './0123456789ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    CONST BLOWFISH_CRYPT_SETTING = '$2a$'; 
    CONST BLOWFISH_CRYPT_SETTING_ALT = '$2y$'; // Available from PHP 5.3.7
    CONST BLOWFISH_ROUNDS = 10;
    CONST BLOWFISH_NAME = 'bcrypt';

    // Note that SHA hashes are not implemented in password_hash() or password_verify() in PHP 5.5
    // and are not recommended for use. Recommend only the default BCrypt option
    CONST SHA256_CHAR_RANGE = './0123456789ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    CONST SHA256_CRYPT_SETTING = '$5$';
    CONST SHA256_ROUNDS = 5000;
    CONST SHA256_NAME = 'sha256';

    CONST SHA512_CHAR_RANGE = './0123456789ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    CONST SHA512_CRYPT_SETTING = '$6$';
    CONST SHA512_ROUNDS = 5000;
    CONST SHA512_NAME = 'sha512';


    /**
     * Default Crypt Algorithm
     * 
     * @var INT
     */
    private $algorithm = PASSWORD_BCRYPT;


    /**
     * Name of the current algorithm
     *
     * @var STRING
     */
    private $algoName;


    /**
     * Setting for PHP Crypt function, defines algorithm
     * 
     * Default setting is '$2a$' : BCrypt
     * 
     * @var STRING
     */
    protected $cryptSetting;


    /**
     * Setting for PHP Crypt function, defines processing cost
     * 
     * Default setting is '08$' for BCrypt rounds
     * 
     * @var INT
     */
    protected $rounds;


    /**
     * Salt Character Count for Crypt Functions
     * 
     * @var INT
     */
    protected $addSaltChars;


    /**
     * Salt Character Range for Crypt Functions
     * 
     * @var STRING 
     */
    protected $saltCharRange;


    /**
     * Class Constructor
     */
    public function __construct(){
        // Initialise default algorithm
        $this-&gt;setAlgorithm($this-&gt;algorithm);
    }


    /**
     * Generate Crypt Password
     * 
     * @param STRING $password The password to encode
     * @param ARRAY $options Cost value, and Salt if required
     * @param BOOL $debug If true will return time to calculate hash
     * @return STRING The encoded password
     */
    public function generateCryptPassword($password, $options = array(), $debug = FALSE){
        $startTime  = microtime(TRUE);
        if (isset($options['cost'])) $this-&gt;setCost($options['cost']);
        $salt       = $this-&gt;cryptSalt(@$options['salt']);
        $crypt      = crypt($password, $salt);
        $endTime    = microtime(TRUE);
        if ($debug){
            $calcTime = $endTime - $startTime;
            return $calcTime;
        }
        return $crypt;
    }


    /**
     * Generate Crypt Salt
     * 
     * Generates a salt suitable for Crypt using the defined crypt settings
     * 
     * @param STRING $salt Override random salt with predefined value
     * @return STRING
     */
    public function cryptSalt($salt=NULL){
        if (empty($salt)){
            for ($i = 0; $i&lt;$this-&gt;addSaltChars; $i++){
                $salt .= $this-&gt;saltCharRange[rand(0,(strlen($this-&gt;saltCharRange)-1))];
            }
        }
        $salt = $this-&gt;cryptSetting.$this-&gt;rounds.$salt.'$';
        return $salt;
    }


    /**
     * Set Crypt Setting
     * 
     * @param type $setting
     * @return \Antnee\PhpPasswordLib\PhpPasswordLib
     */
    public function cryptSetting($setting){
        $this-&gt;cryptSetting = $setting;
        return $this;
    }




       /**
         * Salt Character Count
         * 
         * @param INT $count Number of characters to set
         * @return \Antnee\PhpPasswordLib\PhpPasswordLib|boolean
         */
        public function addSaltChars($count){
            if (is_int($count)){
                $this-&gt;addSaltChars = $count;
                return $this;
            } else {
                return FALSE;
            }
        }


        /**
         * Salt Character Range
         * 
         * @param STRING $chars
         * @return \Antnee\PhpPasswordLib\PhpPasswordLib|boolean
         */
        public function saltCharRange($chars){
            if (is_string($chars)){
                $this-&gt;saltCharRange = $chars;
                return $this;
            } else {
                return FALSE;
            }
        }


        /**
         * Set Crypt Algorithm
         * 
         * @param INT $algo
         * @return \Antnee\PhpPasswordLib\PhpPasswordLib
         */
        public function setAlgorithm($algo=NULL){
            switch ($algo){
                case PASSWORD_SHA256:
                    $this-&gt;algorithm = PASSWORD_SHA256;
                    $this-&gt;cryptSetting(self::SHA256_CRYPT_SETTING);
                    $this-&gt;setCost(self::SHA256_ROUNDS);
                    $this-&gt;addSaltChars(16);
                    $this-&gt;saltCharRange(self::SHA256_CHAR_RANGE);
                    $this-&gt;algoName = self::SHA256_NAME;
                    break;
                case PASSWORD_SHA512:
                    $this-&gt;algorithm = PASSWORD_SHA512;
                    $this-&gt;cryptSetting(self::SHA512_CRYPT_SETTING);
                    $this-&gt;setCost(self::SHA512_ROUNDS);
                    $this-&gt;addSaltChars(16);
                    $this-&gt;saltCharRange(self::SHA512_CHAR_RANGE);
                    $this-&gt;algoName = self::SHA512_NAME;
                    break;
                case PASSWORD_BCRYPT:
                default:
                    $this-&gt;algorithm = PASSWORD_BCRYPT;
                    if (version_compare(PHP_VERSION, '5.3.7') &gt;= 1){
                        // Use improved Blowfish algorithm if supported
                        $this-&gt;cryptSetting(self::BLOWFISH_CRYPT_SETTING_ALT);
                    } else {
                        $this-&gt;cryptSetting(self::BLOWFISH_CRYPT_SETTING);
                    }
                    $this-&gt;setCost(self::BLOWFISH_ROUNDS);
                    $this-&gt;addSaltChars(22);
                    $this-&gt;saltCharRange(self::BLOWFISH_CHAR_RANGE);
                    $this-&gt;algoName = self::BLOWFISH_NAME;
                    break;
            }
            return $this;
        }


        /**
         * Set Cost
         * 
         * @todo implement
         * 
         * @return \Antnee\PhpPasswordLib\PhpPasswordLib
         */
        public function setCost($rounds){
            switch ($this-&gt;algorithm){
                case PASSWORD_BCRYPT:
                    $this-&gt;rounds = $this-&gt;setBlowfishCost($rounds);
                    break;
                case PASSWORD_SHA256:
                case PASSWORD_SHA512:
                    $this-&gt;rounds = $this-&gt;setShaCost($rounds);
                    break;
            }
            return $this;
        }


        /**
         * Set Blowfish hash cost
         * 
         * Minimum 4, maximum 31. Value is base-2 log of actual number of rounds, so
         * 4 = 16, 8 = 256, 16 = 65,536 and 31 = 2,147,483,648
         * Defaults to 8 if value is out of range or incorrect type
         * 
         * @param int $rounds
         * @return STRING
         */
        private function setBlowfishCost($rounds){
            if (!is_int($rounds) || $rounds &lt; 4 || $rounds &gt; 31){
                $rounds = $rounds = self::BLOWFISH_ROUNDS;
            }
            return sprintf("%02d", $rounds)."$";
        }


        /**
         * Set SHA hash cost
         * 
         * Minimum 1000, maximum 999,999,999
         * Defaults to 5000 if value is out of range or incorrect type
         * 
         * @param INT $rounds
         * @return STRING
         */
        private function setShaCost($rounds){
            if (!is_int($rounds) || $rounds &lt; 1000 || $rounds &gt; 999999999){
                switch ($this-&gt;algorithm){
                    case PASSWORD_SHA256:
                        $rounds = self::SHA256_ROUNDS;
                    case PASSWORD_SHA512:
                    default:
                        $rounds = self::SHA512_ROUNDS;
                }
            }
            return "rounds=" . $rounds ."$";
        }


        /**
         * Get hash info
         *
         * @param STRING $hash
         * @return ARRAY
         */
        public function getInfo($hash){
            $params = explode("$", $hash);
            if (count($params) &lt; 4) return FALSE;

            switch ($params['1']){
                case '2a':
                case '2y':
                case '2x':
                    $algo = PASSWORD_BCRYPT;
                    $algoName = self::BLOWFISH_NAME;
                    break;
                case '5':
                    $algo = PASSWORD_SHA256;
                    $algoName = self::SHA256_NAME;
                    break;
                case '6':
                    $algo = PASSWORD_SHA512;
                    $algoName = self::SHA512_NAME;
                    break;
                default:
                    return FALSE;
            }

            $cost = preg_replace("/[^0-9,.]/", "", $params['2']);

            return array(
                'algo' =&gt; $algo,
                'algoName' =&gt; $algoName,
                'options' =&gt; array(
                    'cost' =&gt; $cost
                ),
            );
        }


        /**
         * Verify Crypt Setting
         * 
         * Checks that the hash provided is encrypted at the current settings or not,
         * returning BOOL accordingly
         * 
         * @param STRING $hash
         * @return BOOL
         */
        public function verifyCryptSetting($hash, $algo, $options=array()){
            $this-&gt;setAlgorithm($algo);
            if (isset($options['cost'])) $this-&gt;setCost($options['cost']);

            $setting = $this-&gt;cryptSetting.$this-&gt;rounds;

            return (substr($hash, 0, strlen($setting)) === $setting);
        }
    }
</code></pre>

<p>Final comment: I promise i have searched a lot but not found this particular problem in other questions. Thank you.</p>