I am trying to create a PHP session class to store sessions. What is the best way to deal with sessions?
This is what I have so far:
class Sessions {
function start() {
session_start();
$_SESSION['sid'] = randomstring();
// insert session id into db
// initialize user data
}
function destroy() {
session_destroy();
// delete sid from db too
}
function update() {
session_regenerate_id();
// update lastaccess time in db
}
}
What is the best way to store sessions in PHP?
This will answer your question of Session Handling? http://www.devshed.com/c/a/PHP/Storing-PHP-Sessions-in-a-Database/
Related
I am trying to create a login controller for my website ... in terms of keeping people logged in I've decided to use sessions.
I am currently attempting to create a class that can be referenced when I include the controller file of the sessions. This will allow me to create, authenticate (delete) and update sessions.
<?php
class Session {
static function start($name, $value) {
session_start();
$_SESSION[$name] = $value;
$_SESSION['EXPIRE'] = time() + 10;
}
// checking for expire
static function auth() {
if (isset($_SESSION['EXPIRE']) && $_SESSION['EXPIRE'] < time()) {
$_SESSION = array();
session_destroy();
}
}
static function update($time = 20) {
if (isset($_SESSION['EXPIRE'])) {
$_SESSION['EXPIRE'] = time() + $time;
session_regenerate_id(false);
}
}
}
Currently it does not set sessions properly. When I try to call the sessions on pages once I set them it does not fetch properly.
The session isn't expiring before I call it because I never call the function that expires it inside the class on the document.
You can't call your Session class as you need to include session_start() and you are only having this in the start method.
Option 1: You would have to call session_start() in each page where you want to deal with sessions
Option 2: Add a function to your class and call it after your class is created and add in there session_start() so wherever you include the Session Class session_start would already been initialized
Example:
Sessions.php
class Session {
static function init(){
session_start();
}
//rest of your methods...
}
//initialize it
Session::init();
page-that-uses-session.php
include('Sessions.php');
Session::update();
Better set php session timeout variable in php.ini or from ini_set() function and don't create own $_SESSION['expire'] variable; You can regenerate_session_id() each time when user sent request; Better test user ip address in session. In most projects you have one page on server or only your own pages.
Set user id in session:
$_SESSION['userid'] = $loggoed_id_from_db;
// and test
if((int)$_SESSION['userid'] == 0){
header('Location: logout.php');
exit;
}else{
if(empty($_SESSION['ip'])){
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}else{
if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']){
header('Location: logout.php');
exit;
}
}
}
And probably you don't start session from class!
The session I set is lost after the form is submitted.
I had built the session class to set new session, unset and so on. In function.php of wordpress template.
function.php
if (!session_id()) {
session_start();
}
include get_template_directory() . "/custom/session.php";
Session.php
class session {
function __construct() {
}
function set_flashdata($name, $value) {
$_SESSION[$name] = $value;
}
function flashdata($name) {
if (isset($_SESSION[$name])) {
$str = $_SESSION[$name];
return $str;
} else {
return FALSE;
}
}
function userdata($name) {
if (isset($_SESSION[$name])) {
return $_SESSION[$name];
} else {
return FALSE;
}
}
function set_userdata($name, $value) {
$_SESSION[$name] = $value;
}
function unset_userdata($name) {
if (isset($_SESSION[$name])) {
unset($_SESSION[$name]);
}
}
}
I try to set session as :
<?php
$sess = new session();
$sess->set_userdata('sess_name',"some value");
?>
<form action="get_permalink(212);">
//input buttons
</form>
After submit the form it goes to the permalink(212). Then I tried.
<?php
$sess = new session();
$value = $sess->userdata('sess_name');
var_dump($value); //returns false. That means session is lost after form submit. Why?
?>
You need to move session start/resume into your Session's constructor.
Like so:
class session
{
function __construct()
{
if (! session_id()) {
session_start();
}
}
Another thing to mention, every time you'll do new Session you'll be getting an object of the same functionality working with same global variable $_SESSION.
You don't need more than one $session object, it would be a good time to look into Singleton pattern.
You have to call always session_start() for each request.
The mission of session_start() is:
Creates a new session
Restart an existing session
That means, if you have created a session, and you don't call to the method session_start(), the variable $_SESSION is not going to be fulfilled.
Except: If in your php.ini you have set the option session.auto_start to 1, then, in that case it is not needed to call the session_start() because the variable $_SESSION is fulfilled implicitly.
You need to use wordpress global variable for condition that session is set or not something like :
global $session;
if (!session_id()) {
session_start();
}
include get_template_directory() . "/custom/session.php";
It might be due to www. at the start of your website domain. Make sure that both of pages use the same structure.
Also I faced with the same issue long time ago when the form sends the data to a secured address (https://)
I hope these two items may help you.
Sounds to me like session_start() is not set at the start of the page that get_permalink(212;) refers to.
I have almost no experience with WP itself though, so I might misunderstand the functionality of get_permalink()
I agree with the answer from #rock3t to initialize session in constructor of class, but every time a class object is initiated, it will go to check for session!
Instead, if you are fine, the simplest way to get access to session is by adding following lines to your wp-config.php file before the call to wp-settings
if (!session_id())
session_start();
This will set/initialize session globally and you won't need to set/check for session_start in constructor of a class.
Thank you.
I am trying to save my session into memcached, here is some code:
class MemcacheHandler implements \SessionHandlerInterface
{
public function write($session_id, $session_data)
{
$mc = self::getMc();
# test file
file_put_contents('/tmp/session_test', $session_id.'-'.$session_data.'-'.self::$config['expire'].PHP_EOL, FILE_APPEND);
return $mc->set($session_id, $session_data, self::$config['expire']);
}
# Omitting some code
# read() close() destroy() open() gc() getMc() .....
}
Next
session_set_save_handler(new MemcacheHandler(), true);
session_start();
$_SESSION['uid'] = 123456; # write some data
My question is, when i request to the server, There will be a record in /tmp/session_test like 6n0vam0oo8keadg1nl1qab8633-uid|s:6:"123456";-1200。
But when I refresh the page, no record is written! so, if i set up a user login/logout system using session,Would not it be more than a expire time, the user is automatically dropped?
If I changed $_SESSION['uid'] = 78965; Record will be overwritten。Is not php will determine the session_data has changed before write? If there is no change, no write?
My english is poor。。thanks for your time :)
I use two different sessions for admin and user,and I want to destroy each session separately but when I destroy one session using $this->session->sess_destroy(); it destroys both sessions. Please help me.
$admin_data = array (
'admin_email' => $this->input->post('admin_email'),
'is_admin_logged_in' => 1
);
$this->session->set_userdata($admin_data);
redirect('admin_profile');
public function admin_profile() {
if ($this->session->userdata('is_admin_logged_in')){
$this->load->view("view_admin_profile");
}
else {redirect('login');}
}
public function logout() {
$this->session->unset_userdata($admin_data);
redirect("login");
}
you can use $this->session->unset_userdata('name of session');
for more info check the user-guide
https://www.codeigniter.com/user_guide/libraries/sessions.html
You can use :-
$this->session->unset_userdata('some_name');
unset_userdata() can be used to remove it, by passing the session key
For e.g :
If your admin session name is 'admin_id' and user session id is 'user_id' then you can seperately destroy both the session like this :-
$this->session->unset_userdata('admin_id'); // for admin
$this->session->unset_userdata('user_id'); // for user
To destroy the session in codeigniter simply do this;
function logout() {
$this->session->sess_destroy();
}
I am looking for a way to check on the life of a PHP session, and return the number of seconds a session has been "alive".
Is there a PHP function that I am missing out on?
You could store the time when the session has been initialized and return that value:
session_start();
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
}
And for retrieving that information from an arbitrary session:
function getSessionLifetime($sid)
{
$oldSid = session_id();
if ($oldSid) {
session_write_close();
}
session_id($sid);
session_start();
if (!isset($_SESSION['CREATED'])) {
return false;
}
$created = $_SESSION['CREATED'];
session_write_close();
if ($oldSid) {
session_id($oldSid);
session_start();
}
return time() - $created;
}
I think there are two options neither are great but here they are.
1) If you have access to the file system you can check the creation timestamp on the session file.
2) Store the creation time in the session e.g.
session_start();
if( ! isset($_SESSION['generated'])) {
$_SESSION['generated'] = time();
}
You could simply store the timestamp on which the session was created in the session