Warren
Warren

Reputation: 2024

Basics - Setting and using a session cookie in php?

I'm sure this is a basic question and I'm sure the answer is basic too - apologies if so, but I'm having trouble linking my practical example to the theory I've read.

I'm using the PHPAuth project for my site's authentication. The bit that's got me confused in the notes is the description for the login method that reads:

Authenticates a user with the system. Note: You need to take the returned session hash and create the session cookie, the method does not do this for you.

If a successful login returns:

Array ( [error] => 
        [message] => You are now logged in. 
        [hash] => 374d0de4f97b96b6665c23aa0998dbae1f790fe6 
        [expire] => 0 
      )

What do I actually do with this information to allow the next page to see that a user is logged in?

<?php
require 'vendor/autoload.php';

include("dbconnect-user.php");

$config = new PHPAuth\Config($dbh);
$auth   = new PHPAuth\Auth($dbh, $config);

if (!$auth->isLogged()) {
    header('HTTP/1.0 403 Forbidden');
    echo "Forbidden";
    exit();
}

echo "you are logged in";

?>

I am assuming the above code will handle the session cookie as this is code is almost exactly as the example given by the PHPAuth project so specifically, I'm asking what is meant by the bold text in the above quote.

FYI, the class functions for checking the cooking look like this:

/**
* Returns is user logged in
* @return boolean
*/
public function isLogged() {
    return (isset($_COOKIE[$this->config->cookie_name]) && $this->checkSession($_COOKIE[$this->config->cookie_name]));
}
/**
 * Returns current session hash
 * @return string
 */
public function getSessionHash(){
    return $_COOKIE[$this->config->cookie_name];
}

Upvotes: 0

Views: 991

Answers (2)

Warren
Warren

Reputation: 2024

My previous answer answers my question, but I'm posting this answer in the hope that it may help someone else using the PHPAuth project.

This is my login page:

<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth   = new PHPAuth\Auth($dbh, $config);

if ($auth->isLogged()) {
    echo "You are already signed up and logged in";
    exit();
}

$msg = null;
$showform = true;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    //check for errors
    if (empty($_POST["email"]) ||
        empty($_POST["pwd"]) ) {
        $msg = "All fields are required.";
    } else { //all good - proceed
        $result = $auth->login($_POST["email"], $_POST["pwd"]);
        //check for success
        if ($result["error"] == 1) {
            $msg = $result["message"];
        } else {
            //success
            $msg = $result["message"];
            $showform = false;
            setcookie($config->cookie_name, $result['hash'], time()+3600, "/"); //NOTE: the time can be set with config from the cookie_forget or cookie_remember settings in the PHPAuth config table
        }
    }
}
?>

<html>
<head></head>
<body>
<?php
if ($showform == true) { ?>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <div>
            <label for="email">Email:</label>
            <div>
                <input type="email" name="email" id="email" placeholder="Enter email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
            </div>
        </div>
        <div>
            <label for="pwd">Password:</label>
            <div>
                <input type="password" name="pwd" id="pwd" placeholder="Enter password">
            </div>
        </div>
        <div>
            <button type="submit" name="submit">Submit</button>
        </div>
        <?php echo $msg; ?>
    </form><?php
} else {
    echo $msg . '<br />';
}
?>
</body>
</html>

This is a secured page:

<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth   = new PHPAuth\Auth($dbh, $config);

if (!$auth->isLogged()) {
    header('HTTP/1.0 403 Forbidden');
    echo "Forbidden";
    exit();
}

echo "You are logged in";

?>

And this is a logout script:

<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth   = new PHPAuth\Auth($dbh, $config);

echo $auth->logout($_COOKIE['authID']);
?>

Upvotes: 2

Warren
Warren

Reputation: 2024

The basic answer appears to be this:

Obviously, we need to create the session cookie. In this particular case, the cookie name needs to be the name stored in the config db, "authID".

To do this, I just need to use setcookie see http://php.net/manual/en/function.setcookie.php

In my testing example, on a successful login, I set the cookie and then redirect on a script page like this:

setcookie('authID', $_GET['h'], time() + (86400 * 30), "/");
header('Location: main.php');

Upvotes: 0

Related Questions