I wrote a static Session class that can obviously 'set, get, start but does not destroy' temp user sessions, meaning i have to start a session on each page to be able to destroy it, which make no sense in programming standards.any better way to this approach?
class sessionWrapper {
private static $_sessionStarted = false;
public static function start() {
if(self::$_sessionStarted == false) {
session_start();
self::$_sessionStarted = true;
}
}
public static function set($key, $value) {
$_SESSION[$key] = $value;
}
public static function get($key) {
if(isset($_SESSION[$key])) {
return $_SESSION[$key];
} else {
return false;
}
}
public static function destroy() {
if(self::$_sessionStarted == true) {
session_destroy();
header('Location: $url');
}
}
}
Related
Hy,
i started learning PHP and i created a simple MVC Style Codebase.
The Script just generates a random number and displays this numer. I also write a function to display the number shown before but it does not work. The value is empty. Can you help me out, i have no clue whats wrong and there is no php error thrown.
view.php
<?php
class View
{
private $model;
private $view;
public function __construct()
{
$this->model = new Model();
}
public function output()
{
echo 'Current Entry: ';
echo $this->model->getData();
echo '<br />';
echo 'Update';
echo '<br />';
echo 'Last';
}
public function getModel()
{
return $this->model;
}
}
controller.php
<?php
class Controller
{
private $model;
private $view;
public function __construct($view)
{
$this->view = $view;
$this->model = $this->view->getModel();
}
public function get($request)
{
if (isset($request['action']))
{
if ($request['action'] === 'update')
{
for ($i = 0; $i<6; $i++)
{
$a .= mt_rand(0,9);
}
$this->model->setData($a);
}
elseif ($request['action'] === 'preview')
{
$this->model->setLast();
}
else
{
$this->model->setData('Wrong Action');
}
}
else
{
$this->model->setData('Bad Request');
}
}
}
model.php
<?php
class Model
{
private $data;
private $last;
public function __construct()
{
$this->data = 'Default';
}
public function setData($set)
{
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$this->last = $this->data;
}
$this->data = $set;
}
public function getData()
{
return $this->data;
}
public function setLast()
{
$this->data = $this->last;
}
public function getLast()
{
return $this->last;
}
}
index.php
<?php
require_once 'controller.php';
require_once 'view.php';
require_once 'model.php';
$view = new View();
$controller = new Controller($view);
if (isset($_GET) && !empty($_GET)) {
$controller->get($_GET);
}
$view->output();
Are there any other, bad mistakes in the Script?
Any input very welcome! :)
The problem with your code is that PHP does not preserve variable values between requests, therefore, when you set your $model->last value here:
$this->last = $this->data;
It gets reset on your next request.
You may want to store $last value in a session or a cookie instead. Something like:
$_SESSION['last'] = $this->data;
And then when you are instantiating your model you could initialize it with a value stored in a session if available:
index.php - add session_start() at the beginning
model.php:
public function __construct()
{
$this->data = isset($_SESSION['last']) ? $_SESSION['last'] : 'Default';
}
public function setData($set)
{
$this->data = $set;
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$_SESSION['last'] = $this->data;
}
}
controller.php
elseif ($request['action'] === 'preview')
{
//Remove this
//$this->model->setLast();
}
I have this simple session class
class Session
{
public static function init() {
#session_start();
}
public static function set($key, $value) {
$_SESSION[$key] = $value;
}
public static function get($key) {
if (isset($_SESSION[$key]))
return $_SESSION[$key];
}
public static function destroy() {
unset($_SESSION);
session_destroy();
}
}
In my other class I have
public function verifyFormToken($form)
{
// check if a session is started and a token is transmitted, if not return an error
if(!isset(Session::get($form.'_token'))){
return false;
}
// check if the form is sent with token in it
if(!isset($data['token'])) {
return false;
}
// compare the tokens against each other if they are still the same
if (Session::get($form.'_token') !== $data['token']) {
return false;
}
return true;
}
I can set a session no problem but when I come to get it using verifyFormToken(), i get this error message
Can't use function return value in write context
which points to this line
if(!isset(Session::get($form.'_token'))){
you will have to define a variable as pass that to isset:
$token = Session::get($form.'_token');
if ($token !== NULL) { ... }
or as you are using isset in your get method just do:
if (Session::get($form.'_token') !== NULL) { ... }
EDIT**
In this instance this would be fine, as session token will never be null, but as a session controller, a value may be set as NULL on purpose, or may not be set, so your get method needs to return a unique value to determine whether its set or not. i.e.
define('MY_SESSION_NOT_SET',md5('value_not_set'));
class Session
{
public static function init() {
#session_start();
}
public static function set($key, $value) {
$_SESSION[$key] = $value;
}
public static function get($key) {
if (isset($_SESSION[$key]))
return $_SESSION[$key];
else
return MY_SESSION_NOT_SET;
}
public static function destroy() {
unset($_SESSION);
session_destroy();
}
}
if (Session::get($form.'_token') === MY_SESSION_NOT_SET) { ... }
something like that would be more beneficial.
For some reason when it generates a token it stores another token in the session and it is a completely random token.
Here is my code for the Token class -
class Token {
protected static $token;
public static function generate() {
if(!self::$token){
self::$token = md5(uniqid());
}
return Session::put(Config::get('session/token_name'), self::$token);
}
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
}
And here is my code from my Session class -
class Session {
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
public static function get($name) {
return $_SESSION[$name];
}
public static function put($name, $value) {
return $_SESSION[$name] = $value;
}
public static function delete($name) {
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
public static function flash($name, $string = null) {
if(self::exists($name)) {
$session = self::get($name);
self::delete($name);
return $session;
} else if ($string) {
self::put($name, $string);
}
}
}
Config::get('session/token_name') just returns 'token'
No where else am I generating a new token, and it wouldn't matter anyways as it will just return one token because of the static variable.
Why is WordPress doing this?
Please help I have been trying to get this to work for over 10 straight hours!
For the generate function -
public static function generate() {
if(!Session::get(Config::get('session/token_name'))){
return Session::put(Config::get('session/token_name'), md5(mt_rand()));
}
else{
return Session::put(Config::get('session/token_name'), Session::get(Config::get('session/token_name')));
}
}
This ensures that you only create one for each session.
So I have a class I'm working on to manage PHP sessions, here's the class:
class SessionManagement {
public static function sessionStarted() {
if(session_id() == '') {
return false;
} else {
return true;
}
}
public static function sessionExists($session) {
if(sessionStarted() == false) {
session_start();
}
if(isset($_SESSION[$session])) {
return true;
} else {
return false;
}
}
public static function setSession($session, $value) {
if(sessionStarted() != true) {
session_start();
}
$_SESSION[$session] = $value;
if(sessionExists($session) == false) {
throw new Exception('Unable to Create Session');
}
}
public static function getSession($session) {
if(isset($_SESSION[$session])) {
return $_SESSION[$session];
} else {
throw new Exception('Session Does Not Exist');
}
}
}
Now trying this...
try {
SessionManagement::setSession('Foo', 'Bar');
echo SessionManagement::sessionStarted();
echo SessionManagement::getSession('Foo');
echo SessionManagement::sessionExists('Foo');
} catch(Exception $e) {
echo $e->getMessage();
}
...produces no output...I'm not sure where we're breaking here...any helpful eyes is greatly appreciated...
Unlike other OO languages, like C++, in your class PHP needs to know that the static methods called are from this object. For an instantiated class, that would be through $this, and in your case, static methods, this is done via self:
class SessionManagement {
public static function sessionStarted() {
if(session_id() == '') {
return false;
} else {
return true;
}
}
public static function sessionExists($session) {
if(self::sessionStarted() == false) {
session_start();
}
if(isset($_SESSION[$session])) {
return true;
} else {
return false;
}
}
public static function setSession($session, $value) {
if(self::sessionStarted() != true) {
session_start();
}
$_SESSION[$session] = $value;
if(self::sessionExists($session) == false) {
throw new Exception('Unable to Create Session');
}
}
public static function getSession($session) {
if(isset($_SESSION[$session])) {
return $_SESSION[$session];
} else {
throw new Exception('Session Does Not Exist');
}
}
}
Prepending self:: to all internal calls to the SessionManagement static methods should solve your problem.
I have a class for session handling that uses object overloading for __GET and __SET, I've been having issues with arrays and read to assign get by reference, such as &__GET
The problem is I can't update the values. For example, let's say I have this:
$session->item['one']['name']
I'd like to change it, by assigning it a new value; $session->item['one']['name'] = 'new value' However, it doesn't change.
Any ideas how to work around this? Below is the code, thank you!
class Session
{
private $_session = array();
public function __construct()
{
if(!isset($_SESSION)) {
session_start();
}
$this->_session = $_SESSION;
}
public function __isset($name)
{
return isset($this->_session[$name]);
}
public function __unset($name)
{
unset($_SESSION[$name]);
unset($this->_session[$name]);
}
public function &__get($name)
{
return $this->_session[$name];
}
public function __set($name, $val)
{
$_SESSION[$name] = $val;
$this->_session[$name] = $val;
}
public function getSession()
{
return (isset($this->_session)) ? $this->_session : false;
}
public function getSessionId()
{
return (isset($_SESSION)) ? session_id() : false;
}
public function destroy()
{
$_SESSION = array();
session_destroy();
session_write_close();
unset($this->_session);
}
}
In your constructor, change $this->_session = $_SESSION; to $this->_session = &$_SESSION; so you're getting a reference to it inside of your class.