Logo  

CS479/579 - Web Programming II

Displaying ./code/Sessions/auth.php

<?php

class Auth {
  private $myconn;
  public $error;
  public $sid, $username, $ipaddr;

  function __construct()
  {
    $this->myconn = new mysqli("localhost", "sbaker", "sbaker", "sbaker");
    $this->username = "";
    $this->ipaddr = "";
    $this->error = null;
  }

  function authenticated() {
    if (!isset($_COOKIE['MY_SESSION'])) {
      $this->error = "No session cookie";
      return false;
    }
    $this->sid = $sid = $_COOKIE['MY_SESSION'];

    $stmt = $this->myconn->prepare("SELECT username, ipaddr FROM session WHERE sid=?");
    $stmt->bind_param("s", $sid);
    $stmt->bind_result($this->username, $this->ipaddr);
    $stmt->execute();
    if ($stmt->fetch()) {
      $stmt->close();
      if ($this->ipaddr != $_SERVER['REMOTE_ADDR']) $this->error = "IP Address does not match session IP";
      return true;
    } else {
      $stmt->close();
      $this->error = "No session found";
      return false;
    }
  }

  function createSID()
  {
    // 6 bits worth of character data:
    $cookie_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-@";

    $len = strlen($cookie_chars)-1;
    $sid = "";
    // Loop to generate 126 bits of randomness as a string:
    for ($i = 0; $i < 21; $i++)
      $sid .= $cookie_chars[rand(0, $len)];

    return $sid;
  }

  function newsession($username, $stayloggedin)
  {
    global $myconn;

    // You can use: 2147483647 for the end of time (sometime in 2038):
    $expire = $stayloggedin? time() + 60*60*24*365 : 0;

    setcookie("MY_SESSION", $this->sid = $sid = $this->createSID(), $expire);
    $stmt = $this->myconn->prepare("insert into session (sid, username, ipaddr, expire) values (?, ?, ?, ?)");
    if ($stmt == false) die("newsession" . $this->myconn->error);
    $this->username = $username;
    $this->ipaddr = $addr = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param("sssi",$sid, $username, $addr, $expire);
    $stmt->execute();
    $stmt->close();
  }

  function logout()
  {
    $stmt = $this->myconn->prepare("DELETE FROM session WHERE sid = ?");
    $stmt->bind_param("s", $this->sid);
    $stmt->execute();
    $stmt->close();

    setcookie("MY_SESSION", "", time()-24*60*60);
  }
}

?>