Created
April 9, 2011 19:54
-
-
Save avdg/911715 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// A class to help work with Sessions | |
// In our case, primarily to manage logging users in and out | |
// Keep in mind when working with sessions that it is generally | |
// inadvisable to store DB-related objects in sessions | |
class Session { | |
private $logged_in=false; | |
public $user_id; | |
public $message; | |
public $url; | |
function __construct() { | |
//session_start(); // should be called manual | |
$this->check_message(); | |
$this->check_login(); | |
if($this->logged_in) { | |
// actions to take right away if user is logged in | |
} else { | |
// actions to take right away if user is not logged in | |
} | |
} | |
public static function start() | |
{ | |
session_start(); | |
} | |
public static function set ($key, $value = null) | |
{ | |
$_SESSION[$key] = $value; | |
} | |
public static function get ($key) | |
{ | |
if (isset($_SESSION[$key]) { | |
return $_SESSION[$key]; | |
} | |
return null; | |
} | |
public function is_logged_in() { | |
return $this->logged_in; | |
} | |
public function login($user) { | |
// database should find user based on username/password | |
if($user){ | |
$this->user_id = $_SESSION['user_id'] = $user->id; | |
$this->logged_in = true; | |
} | |
} | |
public function logout() { | |
unset($_SESSION['user_id']); | |
unset($this->user_id); | |
$this->logged_in = false; | |
} | |
public function message($msg="") { | |
if(!empty($msg)) { | |
// then this is "set message" | |
// make sure you understand why $this->message=$msg wouldn't work | |
$_SESSION['message'] = $msg; | |
} else { | |
// then this is "get message" | |
return $this->message; | |
} | |
} | |
public function url($url = "") { | |
if(!empty($url)) { | |
$_SESSION['url'] = $url; | |
} else { | |
return $this->url; | |
} | |
} | |
private function check_login() { | |
if(isset($_SESSION['user_id'])) { | |
$this->user_id = $_SESSION['user_id']; | |
$this->logged_in = true; | |
} else { | |
unset($this->user_id); | |
$this->logged_in = false; | |
} | |
} | |
private function check_message() { | |
// Is there a message stored in the session? | |
if(isset($_SESSION['message'])) { | |
// Add it as an attribute and erase the stored version | |
$this->message = $_SESSION['message']; | |
unset($_SESSION['message']); | |
} else { | |
$this->message = ""; | |
} | |
} | |
} | |
$session = new Session(); | |
$message = $session->message(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment