How can I use session in database table with php and mysql?
You would need to create an object like so:
class SessionHandler
{
private static $lifetime = 0;
private function __construct() //object constructor
{
session_set_save_handler(
array($this,'open'),
array($this,'close'),
array($this,'read'),
array($this,'write'),
array($this,'destroy'),
array($this,'gc')
);
}
public function start($session_name = null)
{
session_start($session_name); //Start it here
}
public static function open()
{
//Connect to mysql, if already connected, check the connection state here.
return true;
}
public static function read($id)
{
//Get data from DB with id = $id;
}
public static function write($id, $data)
{
//insert data to DB, take note of serialize
}
public static function destroy($id)
{
//MySql delete sessions where ID = $id
}
public static function gc()
{
return true;
}
public static function close()
{
return true;
}
public function __destruct()
{
session_write_close();
}
}
Then before session_start initiate this class!
include 'classes/sessionHandlerDB.php';
$session = new SessionHandler();
$session->start('userbase');
$_SESSION['name'] = 'Robert Pitt'; //This is sent to SessionHandler::write('my_id','Robert Pitt')
echo $_SESSION['name']; //This calls SessionHandler::read($id)//$id is Unique Identifier for that
http://php.net/manual/en/function.session-set-save-handler.php
http://php.net/manual/en/function.serialize.php
You control this in php.ini under the session_handler directive. Check out http://www.tonymarston.net/php-mysql/session-handler.html for a easy walk through (used it before).
You'll need to usesession_set_save_handler to write custom open, close, read, write, destroy, and garbage collection functions.
See my github code snippet PHP5.4-DB-Session-Handler-Class for a database driven session management class in PHP 5.4.
Related
It doesn't save my changes after adding a category.
If I add a category, it is seen in the overview, but if I refresh I see the original amount.
I guess there is an error in my Singleton-design but I can't seem to find it.
class ProductService {
private $_database;
public function __construct($databaseType) {
$databaseFactory = new DatabaseFactory();
$this->_database = $databaseFactory->createDatabase($databaseType);
}
public function addCategory($category){
$this->_database->addCategory($category);
}
public function getAllCategories() {
return $this->_database->getAllCategories();
}
}
class DatabaseFactory {
public function __construct() {
}
public function createDatabase($type){
switch ($type) {
case "Memory" :
return MemoryDatabase::getInstance();
}
}
}
class MemoryDatabase {
private $categories;
private function __construct() {
$this->categories = array(
new Category("Cheese"),
);
}
public static function getInstance() {
static $inst = null;
if ($inst === null) {
$inst = new MemoryDatabase();
}
return $inst;
}
private function __clone() {}
private function __wakeup() {}
public function addCategory($category) {
array_push($this->categories, $category);
}
public function getAllCategories() {
return $this->categories;
}
}
Each request you perform in PHP is stateless.
If you want to persist data between requests, you will need to put your data in some form of persistant storage, i.e., sessions, filesystem, database, memory, etc.
Singleton pattern only ensures a single copy of an object is created, for a given request.
class Session{
protected $git = md5(rand(1,6));
public function __construct($config = array())
{
//// some code
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Here I can't assign a random value like this to variable called git. How can I do this if it is possible?
That random value need to be first time generated value only till the time it converts to Null.
Perform random inside your constructor,
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Try setting the value of your variable in your constructor.
constructor will run every time you create an instance of your class.
try this code:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
}
public function _start_session()
{
//code again..
}
}
:)
Declare a variable inside a class,initialize the variables in class inside a constructor, which sets the variables once the object for that class is declared anywhere in the code.
I updated this answer if you want to do not change your session variable on each constructor call then use the below procedure.
class Session{
protected $git;
public function __construct($config = array())
{
$this->git = md5(rand(1,6));
if(!isset($_SESSION['ses_id']))
{
$_SESSION['ses_id'] = $this->git;
}
}
public function _start_session()
{
//code again..
}
}
I hope this helps you.
Try this using a global variable to track the random number:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
if (!isset($GLOBALS['random_val'])) {
$GLOBALS['random_val'] = md5(rand(1,6));
}
$this->git = $GLOBALS['random_val'];
$ses_id = $this->git;
var_dump("Session ID: ".$ses_id);
}
public function _start_session()
{
//code again..
}
}
$ses1 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"
$ses2 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"
I need to use a session information in various functions of my controller, but I can't initialize it in the constructor, because I get an error. Message: Undefined property: Soporte::$session
class Soporte extends MY_Controller {
function __construct(){
parent::__construct( $module, $functionality );
}
public function actualizarSolicitud( $id_solicitud ){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
...
}
public function adminHistorico(){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
$config = array();
...
}
...
}
There's a way to initialize a global variable $user?
Try like below, model is quite complicated so I'm not providing it's code, but you should get the point. Any questions let me know.
/**
* This class is used for performing all read/write session operations
* Native php session is utilized (MY_Session library)
*/
class SessionManager extends BaseLibrary {
private $oUser;
public function __construct() {
parent::__construct();
$this->CI->load->model('User');
}
public function setUser(User $oUser) {
$this->CI->session->set_userdata('userId', $oUser->getId());
}
public function getUser() {
if ($this->oUser === null) {
$this->oUser = new User();
if ($this->CI->session->userdata('userId')) {
$this->oUser->setId($this->CI->session->userdata('userId'));
}
}
return $this->oUser;
}
public function logout() {
$this->CI->session->set_userdata('userId', NULL);
}
}
i have a php page which has some variables regarding database i.e server address, username and password etc.
config.php will include
<?php
$dbserver="";
$username="";
$password="";
$database="";
?>
i have a class which contains all the functions required for my website. How can i import my php page variables into this class to be used for the database connectivity?
my class
<?php
class a{
include("config.php");
function db_connect(){
mysql_connect($dbserver,$username,$password);
}
}
?>
usually for this purpose, Constants exist.
But if you want to use variables, all you have to do is to require_once(yourFile), then when you want to use these variables (which are global) inside a method of a class, simply refer to them as global $myVar; (as if you're declaring it). Only need to do this once for each global variable you want to use in the context.
Example:
settings.php:
$conn = 'my connection';
MyClass.php:
class MyClass
{
function DoSomething()
{
require_once('settings.php');
global $conn;
doSomethingWith($conn);
}
}
Update
For a Database class that requires configuration options, the simplest way would be to use the config values as parameters (example 1 of my original answer below).
A more complex, though also more flexible approach would be a Config-Class.
class Config
{
private $config = array();
public function __construct(array $config)
{
$this->config = $config;
}
public function Register($key, $value)
{
$this->config[$key] = $value;
}
public function Get($key)
{
if (!isset($this->config[$key])) return null;
return $this->config[$key];
}
}
Your DB class would look something like this:
class Database
{
private $config = null;
public function __construct(Config $config)
{
$this->config = $config;
}
public function Connect()
{
do_connect_stuff($this->config->Get('host'), $this->config->Get('user'), .....);
}
}
File config.php
<?php
$config = new Config(
array(
"host" => "localhost",
"user" => "user",
...
)
);
/*
alternative:
$config = new Config();
$config->Register('host', 'localhost');
$config->Register('user', 'user');
...
*/
?>
File that requires the database:
<?php
$database = new Database($config);
$database->Connect();
?>
As a side hint: Use PDO, it's far better than the old mysql_* functions.
Original Answer
The proper style would be to pass the variables to the functions as parameter or pass them when creating the object. You can also use Init methods to pass the parameters.
Examples:
(Which of the following code you should use depends on what you already have and how your code is designed, the 'cleanest' way would be an object for which you transmit the variables when calling the ProcessAction method)
Assuming that in your script you have a Variable $action which you get from $_GET or some other way.
Using an Object
class Controller
{
public function ProcessAction($action, $some_other_parameter, $and_yet_another_parameter)
{
[...]
}
}
You then call it with
$action = do_some_stuff_to_get_action();
$controller = new Controller();
$controller->ProcessAction($action, $other_parameter, $second_parameter);
Using a static class
class Controller
{
public static function ProcessAction($action, $some_other_parameter, $and_yet_another_parameter)
{
[...]
}
}
Called with:
$action = do_some_stuff_to_get_action();
Controller::ProcessAction($action, $other_parameter, $second_parameter);
Passing the parameters before calling the function
Object
class Controller
{
private $action = "";
private $some_other_parameter = "";
public function __construct($action, $some_other_parameter)
{
$this->action = $action;
$this->some_other_parameter = $some_other_parameter;
}
public function ProcessAction()
{
if ($this->action == 'do_stuff')
{
[...]
}
}
}
Called with:
$action = do_some_stuff_to_get_action();
$controller = new Controller($action, $other_parameter);
$controller->ProcessAction();
Static methods
class Controller
{
private static $action = "";
private static $some_other_parameter = "";
public static function Init($action, $some_other_parameter)
{
self::$action = $action;
self::$some_other_parameter = $some_other_parameter;
}
public static function ProcessAction()
{
if (self::$action == 'do_stuff')
{
[...]
}
}
}
Called with:
$action = do_some_stuff_to_get_action();
Controller::Init($action, $other_parameter);
Controller::ProcessAction();
I used the database configuration in the constructor of the class. I think that was the only solution not including any third page in the scenario.
Basically, what I want to do is create a class called Variables that uses sessions to store everything in it, allowing me to quickly get and store data that needs to be used throughout the entire site without working directly with sessions.
Right now, my code looks like this:
<?php
class Variables
{
public function __construct()
{
if(session_id() === "")
{
session_start();
}
}
public function __set($name,$value)
{
$_SESSION["Variables"][$name] = $value;
}
public function __get($name)
{
return $_SESSION["Variables"][$name];
}
public function __isset($name)
{
return isset($_SESSION["Variables"][$name]);
}
}
However, when I try to use it like a natural variable, for example...
$tpl = new Variables;
$tpl->test[2] = Moo;
echo($tpl->test[2]);
I end up getting "o" instead of "Moo" as it sets test to be "Moo," completely ignoring the array. I know I can work around it by doing
$tpl->test = array("Test","Test","Moo");
echo($tpl->test[2]);
but I would like to be able to use it as if it was a natural variable. Is this possible?
You'll want to make __get return by reference:
<?php
class Variables
{
public function __construct()
{
if(session_id() === "")
{
session_start();
}
}
public function __set($name,$value)
{
$_SESSION["Variables"][$name] = $value;
}
public function &__get($name)
{
return $_SESSION["Variables"][$name];
}
public function __isset($name)
{
return isset($_SESSION["Variables"][$name]);
}
}
$tpl = new Variables;
$tpl->test[2] = "Moo";
echo($tpl->test[2]);
Gives "Moo".