Giter Club home page Giter Club logo

wp-session-manager's Introduction

WP Session Manager Build Status Coverage Status

Session management for WordPress.

Description

Adds $_SESSION functionality to WordPress, leveraging the database where needed to power multi-server installations.

Every visitor, logged in or not, will be issued a session. Session data will be stored in the WordPress database by default to deal with load balancing issues if multiple application servers are being used. In addition, the session collection will also be stored in memory for rapid use within WordPress.

Session data stored in the database can be encrypted at rest for better security.

Installation

Manual Installation

  1. Upload the entire /wp-session-manager folder to the /wp-content/plugins/ directory.
  2. Activate the plugin through the 'Plugins' menu in WordPress.
  3. Use $_SESSION in your code.

Frequently Asked Questions

How do I add session variables?

Merely use the superglobal $_SESSION array:

$_SESSION['user_name'] = 'User Name';                            // A string
$_SESSION['user_contact'] = array( 'email' => '[email protected]' ); // An array
$_SESSION['user_obj'] = new WP_User( 1 );                        // An object

How long do session variables live?

This depends on your PHP installation's configuration. Please read the PHP manual for more details on configuration.

Can I use this plugin without creating new tables?

Absolutely! As of version 2.0, this plugin will create a new table for WordPress to store session data. In general, this is more efficient long-term than using options for data storage. However, if your system does not allow creating a table, add the following to wp-config.php to use the options table instead:

define( 'WP_SESSION_USE_OPTIONS', true );

I get an error saying my PHP version is out of date. Why?

PHP 5.6 was designated end-of-life and stopped receiving security patches in December 2018. PHP 7.0 was also marked end-of-life in December 2018. The minimum version of PHP supported by WP Session Manager is now PHP 7.1.

If your server is running an older version of PHP, the session system will not work! To avoid triggering a PHP error, the plugin will instead output this notice to upgrade and disable itself silently. You won't see a PHP error, but you also won't get session support.

Reach out to your hosting provider or system administrator to upgrade your server.

I get an error saying another plugin is setting up a session. What can I do?

WP Session Manager overrides PHP's default session implementation with its own custom handler. Unfortunately, we can't swap in a new handler if a session is already active. This plugin hooks into the plugins_loaded hook to set things up as early as possible, but if you have code in another plugin (or your theme) that attempts to invoke session_start() before WP Session Manager loads, then the custom handler won't work at all.

Inspect your other plugins and try to find the one that's interfering. Then, reach out to the developer to explain the conflict and see if they have a fix.

Screenshots

None

Changelog

4.2.0

  • Update: Change donate link to Patreon vs PayPal.
  • Fix: Disable the initialization routine for cron runs.

4.1.1

  • Fix: Defensively protect deprecated functions with function_exists() checks to avoid conflicts with other systems.
  • Fix: Disable the initialization routine if sessions are disabled.

4.1.0

  • Fix: Add some defense to ensure end users are running the correct version of PHP before loading the system.
  • Fix: Eliminate a race condition where another plugin or the theme created the session first.
  • Fix: Schedule a cron to auto-delete expired sessions.

4.0.0

  • New: Add an object cache based handler to leverage Redis or Memcached if available for faster queries.
  • New: Adopt the Contributor Covenant (v1.4) as the project's official code of conduct.
  • Update: Bump minimum PHP requirements due to out-of-date version deprecations.
  • Fix: Correct a race condition where a session was created before the database table existed.
  • Fix: Correct a race condition where the $wpdb global is not yet set when a session is deleted from the database.
  • Fix: Remove unnecessary integer session ID from the stored data table.

3.0.4

  • Update: Add support for the wp_install hook to create custom table immediately.

3.0.3

  • Fix: Repair code blocks in the readme
  • Fix: Use a more defensive approach to starting sessions in the event another plugin has started one already

3.0.2

  • Fix: Add back in proper array access support for the deprecated WP_Session object.

3.0.1

  • Update: Pull a Sessionz fix

3.0.0

  • Update: Refactor to use Sessionz
  • Update: Add encryption at rest if WP_SESSION_ENC_KEY is set

2.0.2

  • Fix: Wire the data storage migration to a session init hook to ensure it runs.
  • Fix: Clean up sessions when all data is removed.

2.0.1

  • Fix: Repair data storage that was not returning actual stored session data.

2.0.0

  • Update: Use a table instead of options for storing session data.

1.2.2

  • Update: Use regex pattern matching to ensure session IDs are identical going in/out of the DB to account for encoding differences

1.2.1

  • Update: Additional filters for the setcookie parameters
  • Update: Expose the Session ID publicly
  • Fix: Better handling for malformed or broken session names

1.2.0

  • Update: Enhanced plugin organization
  • Update: Added WP_CLI support for session management
  • Update: Add Composer definitions
  • Fix: Break up the deletion of old sessions so queries don't time out under load

1.1.2

  • Fix a race condition where session expiration options could accidentally be set to autoload
  • Make the garbage collection routine run hourly to alleviate long-running tasks on larger sites

1.1.1

  • Fix a bug where session expiration was not properly set upon instantiation

1.1

  • Implement Recursive_ArrayAccess to provide multidimensional array support
  • Better expiration for session data
  • Implement garbage collection to keep the database clean

1.0.2

  • Switch to object persistence rather than transients

1.0.1

  • Changes implementation to avoid the use of a global variable (still registered for convenience)

1.0

  • First version

Upgrade Notice

4.0 This version requires PHP 7.1 or higher.

3.0 This version requires PHP 5.6 or higher and uses Composer-powered autoloading to incorporate Sessionz for transparent session management.

2.0

This version will create a new database table for storing session data! If you do not want such a table, please set the WP_SESSION_USE_OPTIONS constant to true in wp-config.php! Upgrading will delete all existing sessions!

1.0

First version

Additional Information

Contributors: ericmann
Donate link: https://www.patreon.com/user?u=16402577
Tags: session
Requires at least: 4.7
Tested up to: 5.1.1
Requires PHP: 7.1
Stable tag: 4.2.0
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html

wp-session-manager's People

Contributors

anhskohbo avatar chrisguitarguy avatar crxgames avatar ericmann avatar griffbrad avatar julien731 avatar kai-jacobsen avatar lewayotte avatar nciske avatar pderksen avatar pippinsplugins avatar pjeby avatar szepeviktor avatar tollmanz avatar truongwp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wp-session-manager's Issues

Delete old sessions when accessed instead of deleting proactively

WP_Session::touch_session() worries me when you have a large number of sessions stored. To iterate over everything in the "_wp_session_list" and check the values against the current time could be a costly operation. I did a few quick tests of this in my local environment (read: not at all scientific) and found that for every 1000 sessions stored, it took ~0.01 seconds to loop through the sessions when the WP_Session object is constructed and ~0.02 seconds when "touch_session" is called on the shutdown function (I have no reason why it takes longer during shutdown).

I think this presents a scalability concern that could be addressed now, rather than later. I can think of a few options that could potentially address the issue:

  1. Avoid it completely: I think you should implement something like what is used with transients in that when a session is accessed, it checks to see if the transient is expired. If the transient is found and the time is expired, the transient is deleted and the function returns false. Similarly, you can more performantly look up the individual hash in the "_wp_session_list" array to see if it is expired. If it is, delete session row, remove the hash from the "_wp_session_list" option and return false (or I guess create the new session).

  2. More closely mimic transients: Transients record the expiration time as a new row in the wp_options table. Perhaps if you do the same, you can do a quick query to look for the expired sessions. You can either proactively delete them or utilize this somehow to delete them as suggested in #1.

  3. Utilize the expiration time in the cookie to determine whether or not to reset the current user's session. This avoids a MySQL lookup and an expensive iteration.

Additionally, if there is concern that this could lead to old sessions from 1 time visitors filling the database, you could set up a scheduled event to purge these old values.

$wp_session vs $_SESSION vs WP_Engine

Hey Eric,

I realize you guys moved the plugin up to v3 and started using the native $_SESSION.

However, $_SESSION is disabled on WP-Engine platforms, and I was using a previous version of your plugin as a makeshift $_SESSION var.

Was there a philosophical reason to move to $_SESSION? Is there a fork with the functionality being still aligned with $wp_session or something similar? Thanks in advance.

Expiration time

Hello!

Amazing plugin, just added to WooCommerce on a host that didn't support persistent carts and it's all saved now.

The only question I have is where exactly (which file and position in the code) do I insert the session expiration length?

add_filter( 'wp_session_expiration', function() { return 60 * 60; } ); // Set expiration to 1 hour

Is it possible to make session indefinite, i.e. not expire? At the very least I would like to set the expiration time to 1 week. Please advise. Thank you.

Add Contributing Developer Credits

This is a sticky issue.

On the one hand, adding your WP.org usernames to the plugin is easy. But since the goal is to get this implemented in core, there's no easy way to list everyone's names.

We could through a bunch of @author tags in the PHPDocs, but WordPress as a whole doesn't do that. So, how would you all like to be credited for your contributions to the project?

PHP Warning: delete_old_sessions()

Getting a PHP Warning:
Invalid argument supplied for foreach() in /includes/class-wp-session-utils.php on line 86

Triggered by:
WP_Session_Utils::delete_old_sessions() /includes/wp-session.php:131

Where / when should I add the filter: wp_session_expiration

Hi.

I'm having troubles figuring out how to get the filter to work. I've tried placing it directly in functions.php and also in a after_setup_theme action but to no avail.

If you could be so kind to give me a hint on where to run the filter.

add_filter( 'wp_session_expiration', function() { return 60 * 60; } ); // Set expiration to 1 hour

Much appreciated
.rickard

Session Fails after if else

Hello on one single page -
I start from -
if(session_id() == '') session_start(); /of course its in index.php I just written for the plugin stuff/

$wp_session = WP_Session::get_instance();
then based on an parameter received in URL which will not be always there -
so for example
--url--?test=1
if($_GET['test']){
$wp_session['test'] = 'testing';
}

On second run ---url--- no parameters
and I want to check
if($wp_session['test']){
}else{
}
Get nothing here

session->reset seems to succeed, but data returns to container array

Hi and thank you for your visionary work, man.

I'm using version 2.0.2 kind of like EDD does within a plugin.

When I run session->reset(), the container array is cleared, but then seems to still contain the previous data in memory, as well as in the database, with the same session_id.

I even tried running session->write_data(), to my "logout" routine, which it looks like should either destroy the session or overwrite the session_value in the database, but doesn't.

If I run delete_session() the database entry is cleared, but the session seems to persist in memory (minus the container data). Is this because the session was just started and expires and exp_variant are configured to store the data via a $_COOKIE?

I saw reference to documentation in the issues, but haven't been successful finding it so apologies if this is a spammy thread.

Happy Summer and thanks.

Move sessions to a custom table

We've been this plugin as it came bundled with another one. We've got a relatively busy site and that results in loads of sessions being generated.

In a year's time and whilst the business is still growing our options table has reached an auto increment value of 29m (obviously not all of them come from this plugin). We gave adjusted the garbage collection to clear all expired sessions, however we still have a lot of unecessary data and read/writes on our options table. This slows down all pages as most plugins and core use the options table on every page load.

Having read #36 seems obvious you understand the necessity of moving away from the options table on onto a custom one. If that table is well written, it would make it a breeze to manage sessions, just like WooCommerce has done with their sesssion management table and would not affect any other parts of the site.

Considering it's now over a year and a half after you commented on #36 and over half a year since #42 (which still doesn't appear to use a new table), i wonder if this plugin is still actively maintained, or not.

I appreciate you're probably busy with other stuff and creating v2 is probably a low priority at this stage, but looking at your code, a refactor of the session storage doesn't appear to be a major change.

I wouldn't mind sending a pull request, assuming you'd merge it, so we can get this implemented soon (weeks, rather than months).

Ability to get reference to container

Currently, you can't use array_push or array_pop with WP_Session.

The following won't work:

<?php
$wp_session = WP_Session::get_instance();
array_push($wp_session, 'Hello World!');
array_pop($wp_session);

I propose adding a method to Recursive_ArrayAccess that returns a reference to the container:

<?php
class Recursive_ArrayAccess implements ArrayAccess, Iterator, Countable {
    /**
     * Internal data collection.
     *
     * @var array
     */
    protected $container = array();

    // ...

    /**
     * Returns a reference to the data container.
     *
     * @return array
     */
    public function &toArrayRef() {
        return $this->container;
    }
}

Then the following would work:

<?php
$wp_session_array = WP_Session::get_instance()->toArrayRef();
array_push($wp_session_array, 'Hello World!');
array_pop($wp_session_array);

Get rid of global $wp_session variable

As I understand it, the point of using a singleton is to avoid using global variables and avoid unwanted tampering with the objects the code makes assumptions about. Perhaps it makes more sense to replace all instances of global $wp_session with $wp_session = WP_Session::get_instance();?

I'd be happy to send a pull request, but I wanted to bring it up here in an issue first, so there could at least be some discussion.

Thoughts?

Table errors on first activation

Hello,

Just started using this plugin and when you first activate it you get the errors:

[Table '[db_name].wp_sm_sessions' doesn't exist]
SELECT * FROM wp_sm_sessions WHERE session_key = '*********************'

WordPress database error: [Table '[db_name].wp_sm_sessions' doesn't exist]
SHOW FULL COLUMNS FROM `wp_sm_sessions`

After that it seems to create the tables and is fine.

Add basic unit tests

Not everything is testable or in a state where we even can test things. But we should wire up a few basic things with Travis to ensure nothing breaks during refactoring

Question about updating sessions

Hello Eric,

thanks for your libraries. I know you're currently rewriting the code, but I was wondering if you could elaborate on why you chose to call delete_option() followed by add_option() when updating the sessions in class-wp-session.php, rather than just calling update_option()?

What am I missing here?

Remove option when session has been emptied

We're implementing #47 in Charitable but just discovered a problem related to this: If you previously had stored things in session that you now want to remove, leaving you with an empty container, your container will not get updated.

There should be a check that if the container is empty but was not empty before, the option should be deleted.

As an alternative, would it be sufficient to just check whether dirty is true?

  • If dirty is not true, nothing has changed, so we have nothing to store.
  • If dirty is true and the container is empty, delete the options.
  • If dirty is true and the container has contents, update/add the options.

Compatibility BROKEN with PHP 5.6 in 4.0!

php --version
PHP 5.6.39-0+deb8u1 (cli) (built: Dec 16 2018 21:56:53)

Since the last update, compatibility to PHP 5.6 is broken.

Getting multiple errors like these:
PHP Parse error: syntax error, unexpected ':', expecting '{' in /xxx/wp-content/plugins/wp-session-manager/includes/deprecated.php on line 15,

This is causing http 500 errors on wordpress sites using this plugin.

Persisting across multisite

Hi Eric,

Great plugin.

Except for my uses, I needed it to be saving it to the site-wide options table (sitemeta) in multisite. I just went ahead and changed all the option getter and setter functions to site_option equivalents in the class definition, and then modified the cleanup code so its cleaning up the sitemeta table rather than options.

I am far from a WordPress ninja, so I'm writing primarily to ask if I've misunderstood something about how the plugin works. I think I got it right, and it seems to be behaving well on my test server right now, but I'm hesitant to deploy into production until I feel more certain. Any feedback is greatly appreciated if you find the time.

I'm also posting here in case someone else runs into this issue. Eric, if you can think of an official way to work this into the plugin as some kind of option, that might be helpful. Of course, I'm happy to help any way I can.

-- Damir

Use transients instead of options

Right now the plugin adds and deletes sessions as options, which means that each user session will get stored in the wp_options table (two options per user session). If a site has a lot of traffic, this can make the wp_options table huge.

Instead of using options functions, it should be using transients. That way if an object cache (e.g. memcached) is available, then it can skip the wp_options table altogether.

PHP Warning: Cannot modify header information

Hi Eric,

first thanks for your sharing wp-session-manager, I am using it in our WordPress mapping plugins Leaflet Maps Marker and Maps Marker Pro, supporting the throtteling of requests to geocoding engines.

I got a report from a user today about the following PHP error log
entry:

PHP Warning: Cannot modify header information - headers already sent by (output started at /wp-includes/functions.php:3673) in /wp-content/plugins/leaflet-maps-marker/inc/Stiphle/Storage/Session/class-wp-session.php on line 134

Related code (line 134 = return setcookie...)

	protected function set_cookie() {
         	$secure = apply_filters('wp_session_cookie_secure', false);
         	$httponly = apply_filters('wp_session_cookie_httponly', false);
			return setcookie( WP_SESSION_COOKIE, $this->session_id . '||' . 
$this->expires . '||' . $this->exp_variant , $this->expires, COOKIEPATH, COOKIE_DOMAIN, $secure, $httponly );
	}

As I couldn´t really reproduce this issue, I wonder if you have an idea what causes this and how this warning could be avoided.
Any hint would be much appreciated!
best,

Robert

Call to a member function delete() on null

Hi!

I’m seeing this error in apache error log many times in a row:

Call to a member function delete() on null /wp-content/plugins/wp-session-manager/includes/DatabaseHandler.php on line 205

Do you know what could be causing it? I’m running the latest plugin version.

Cheers!

Session creation race conditions

Reported in the WordPress forums => https://wordpress.org/support/topic/php-7-2-warning-5/

If another plugin or the theme sets up the session before we hook in, PHP 7.2 will trigger a warning pointing out that we've tried to reset the save handler after a session is already active. We need to hook in as early as possible and trigger our own error if something has interfered with the system's normal path of operation.

Add wp_install hook

Hi Eric,

Could you also add the following hook:
add_action('wp_install', ['EAMann\WPSession\DatabaseHandler', 'create_table']);

This will make sure that when plugins are activated on wp_install, your plugin can create the necessary tables.

Thanks in advance!

Transient handler

@ericmann Do you plan to add transient handler?
We use Redis, so it would expire by itself and would not stress the database.

How to get the session ID?

Is there a specific reason why the session ID is not accessible? I now use the following code to retrieve the session ID:

$session_id = substr( filter_input( INPUT_COOKIE, WP_SESSION_COOKIE, FILTER_SANITIZE_STRING ), 0, 32 );

It would be nice if the session ID is al available trough an public function.

$wp_session = WP_Session::get_instance();
$session_id = $wp_session->get_session_id();

If there is an specific reason why it's not accessible then that's ok to. Maybe it's nice to mention this in the comments of the session ID property:

https://github.com/ericmann/wp-session-manager/blob/1.1.2/class-wp-session.php#L20-L25

Getting the session manager to work on WPEngine

Hey @ericmann, thanks for the great plugin, we are hosting our site on WPE currently which has some aggressive caching in place. We have had _wp_session excluded on that cache, however seeing a behaviour where in incognito mode the cookie does not get set, thereby none of the session functions working. I believe WPE uses memcached for their object storage. Can you shed any light on this?

Using it without a wp plugin

as the title says, is it possible to use it as an object package and not as a wp plugin?
Or it must be used as a plugin, i was thinking to fork and redo the implementation so it can support psr4 and supports usage without needing to install it as a plugin in wp.

Github versions vs Wordpress plugin page version

I've noticed the version in the GH repo is 1.2.0 and the WP Plugin page shows 1.1.2.

I presume the WP Plugin page version is not up to date? Any plans to update this?

Also, is version 1.2.0 compatible with WP 4.1?

Thanks.

3.0 breaks any plugin expecting a WP_Session object

In 3.0, you're now just returning the $_SESSION super-global from the WP_Session::get_instance() method. This breaks any plugin that was checking that an object was a WP_Session (either with instanceof or a type hint).

To preserve backward compatibility, it should be possible to instead continue returning a WP_Session object from get_instance(). The array access methods in WP_Session would be different than the 2.0 versions in that they'd only be reading from and writing to $_SESSION internally, but you'd avoid breaking any plugins expecting a WP_Session object.

Does that make sense? Would it be helpful if I wrote this up and submitted a patch?

Thanks for your work on 3.0. I can tell a lot of effort went into it.

Update session in DB when call reset()

I think we should make an update to DB when calling reset, i suppose within reset() function we add this line:

public function reset() {
$this->container = array();
//update data to DB
update_option( "wp_session{$this->session_id}", $this->container);
}

wp_session_unset

Hi,

I have a problem with the wp_session_unset() method.

I took note of issue #12.

I've created a function in my functions.php file, that is called when I click a button (via admin-ajax.php). The purpose of this function is simply to unset my session.
When I execute it, and then get the session instance again and dump it right after (I'm not dumping the previously assigned local variable) , the session has been properly unset.

But if I navigate to another page where I'm just retrieving the session instance and dumping it, it still shows me the full previous session.

How can I get 2 different output when dumping the WP_Session::get_instance() ?

EDIT: I can unset a session variable by doing this:
wp_session = WP_Session::get_instance();
unset(wp_session['var_name']);

Thanks for your help.
Cédric

Tables aren't created if activated via wp-cli

If you activate the plugin via wp plugin activate, the DB table isn't created, and subsequent attempts to use the plugin generate errors. Adding this line to the main plugin file fixed the issue for me:

register_activation_hook(__FILE__, ['EAMann\WPSession\DatabaseHandler', 'create_table']);

[Feature Request] Implement Iterator interface in Recursive_ArrayAccess class

Hello,
you're plugin is great, however a missing feature makes it difficult to use it. The Recursive_ArrayAccess class doesn't implement support for iterators, this means that I can't loop the container object to get all data stored as an array without using the toArray method. I spent hours trying to figure out why I couldn't use the foreach because of this, so my proposal is to implement the Iterator interface. It would be cool also to release a new version of the plugin with the compatibility flat set up to 4.0. Thank you and keep up your good work!

SQL injection attempts in wp_session option names

I just spent a dumb amount of time debugging why sessions weren't being garbage collected (there were 785,000+ entries in the wp_options table matching _wpsession%), and eventually found out there were SQL injection attempts causing a SQL error in the cronjob DELETE call. Here are some of the nefarious names in question:

'_wp_session_fe6264b27973c947e939295a9b280c67',
'_wp_session_expires_aa2f368b8b6c02591eec53f93c3aeb3f',
'_wp_session_aa2f368b8b6c02591eec53f93c3aeb3f',
'_wp_session_expires_-1 AND (/*!SElEcT*/ 8041 FRoM(/*!selEcT*/ COUNT(*),CONCAt((/*!SelEcT*/ concat(0x7c3a3a3a3a,substring(database(),1,52),0x3a3a3a3a7c) ),floor(rand(0)*2))x FRoM INFORMATION_S',
'_wp_session_-1 AND (/*!SElEcT*/ 8041 FRoM(/*!selEcT*/ COUNT(*),CONCAt((/*!SelEcT*/ concat(0x7c3a3a3a3a,substring(database(),1,52),0x3a3a3a3a7c) ),floor(rand(0)*2))x FRoM INFORMATION_S',
'_wp_session_expires_-1' AND (/*!SElEcT*/ 8041 FRoM(/*!selEcT*/ COUNT(*),CONCAt((/*!SelEcT*/ concat(0x7c3a3a3a3a,substring(database(),1,52),0x3a3a3a3a7c) ),floor(rand(0)*2))x FRoM INFORMATION_',
'_wp_session_-1\' AND (/*!SElEcT*/ 8041 FRoM(/*!selEcT*/ COUNT(*),CONCAt((/*!SelEcT*/ concat(0x7c3a3a3a3a,substring(database(),1,52),0x3a3a3a3a7c) ),floor(rand(0)*2))x FRoM INFORMATION_',
'_wp_session_expires_-1" AND (/*!SElEcT*/ 8041 FRoM(/*!selEcT*/ COUNT(*),CONCAt((/*!SelEcT*/ concat(0x7c3a3a3a3a,substring(database(),1,52),0x3a3a3a3a7c) ),floor(rand(0)*2))x FRoM INFORMATION_',
'_wp_session_-1\" AND (/*!SElEcT*/ 8041 FRoM(/*!selEcT*/ COUNT(*),CONCAt((/*!SelEcT*/ concat(0x7c3a3a3a3a,substring(database(),1,52),0x3a3a3a3a7c) ),floor(rand(0)*2))x FRoM INFORMATION_',
'_wp_session_expires_e7d721fbe224e5869829bf684b164c99',
'_wp_session_e7d721fbe224e5869829bf684b164c99',
'_wp_session_expires_5b93f49f190aa8c361af00f4407cb214',
'_wp_session_5b93f49f190aa8c361af00f4407cb214'

I'm using the plugin in a Bedrock/Sage setup (https://github.com/firebelly/scb). I'm not sure how these were able to be injected (any ideas?), but the cronjob could be adjusted to use $wpdb->escape() instead of addslashes() to at least not bomb if this came up.

Avoid unnecessary database writes

I am concerned about two areas that write data to the database: 1) touch_session, and 2) wp_session_write_close.

  1. When WP_Session is instantiated, the WP_Session::touch_session() method is executed. Since this is initiated on "plugins_loaded", this guarantees a database write on every page load, which is a significant performance concern. From my reading of the WP_Session::touch_session() method, it appears that this is attempting to remove expired sessions from the database. Would it make sense to only run "update_option" in the WP_Session::touch_session() method if an expired session was found? I do not see a reason to run it on every page load.

  2. From looking at "wp_session_write_close", I assume that the session data is written to the database on "shutdown" to give an experience much like native PHP sessions in that if data is written to the $_SESSIONS array, it is written to disk. This prompts a concern in that it uses another database write on every page load, even if it is not needed. Would it make sense to check and see if the data in WP_Session::container has changed from when it was loaded before actually performing the write?

I think there would be a major performance boost if writes are performed only when absolutely necessary and we can get rid of two such writes with rather simple changes.

Request: Shortcode to echo session variables via editor

This is rough untested code... What do you think of the idea? I can't imagine that I am the only one who wants this...

function wpsession_shortcode( $atts ) {

    $wp_session = WP_Session::get_instance();

    // Attributes
    extract( shortcode_atts(
        array(
            'var' => '',
        ), $atts )
    );

    return $wp_session['var'];
}
add_shortcode( 'wpsession', 'wpsession_shortcode' );

Doesn't work on Flywheel or Pantheon

I'm using WP Session Manager on a variety of hosts, but it doesn't work on Flywheel or Pantheon sites in my testing.

If you inspect the cookies, the _wp_session value does not stay the same between page refreshes or redirects.

I'm still investigating but wanted to start a thread on this in case anyone else has any insight or thoughts.

Documentation enhancement to reduce wp_session_expiration grief

The code works great but it seem to be confusion around the web about how to use it. It tripped me also before I actually read the comments in class-wp-session.php. I think it could be addressed by mentioning the wp_session_expiration_variant in the readme.md.

When debugging sessions its commonplace to make them short lived. The effect of just lowering the wp_session_expiration to lets say 3 minutes, is that you will get a new session every third minute regardless of how many times you hit the site. This is a bit confusing until you realize that the wp_session_expiration_variant also need to be lowered. It must in fact always be the lowest value of the two and I think this isn't clear enough.

/* This code will create a session that lives for 120 seconds and the 
time will be updated when less than 60 seconds remain. */
add_filter( 'wp_session_expiration', function() { return 120; } );
add_filter( 'wp_session_expiration_variant', function() { return 60; } );

Database sessions not automatically clearing

From: https://wordpress.org/support/topic/understanding-confirmation-sessions-expiration-and-session-gc_probability/

I would like confirmation that I am understanding the following correctly.

While using WP Session Manager, I am seeing MANY stale sessions that do not delete themselves from the database. I am in an Ubuntu hosted environment where session.gc_probability is set to zero. This appears to be a default thing for Ubuntu/Debian. For those environments, expired session cleanup is done by way of a cron task – BUT those environments assume file-based sessions, not database sessions (such as WP Session Manager provides).

For such a scenario, would I be correct that I need to do session cleanup for expired sessions myself? Probably a short cron task that calls DataManager::clean()?

Session will live for only 24 minutes no matter what

Hi Eric,

First of all, amazing plugin!

My problem.
It seems to me that no matter what, the sessions will only live for 24 minutes. If I read a session variable after it has been set 10 minutes ago, the expiration should reset to 24 minutes, right?

"By default, session variables will live for 24 minutes from the last time they were accessed - either read or write."

I use the following code to set an variable on page load

$wp_sessions = WP_Session::get_instance();
$wp_sessions['id'] = $id;

and use the following to read. If session doesn't exist, I redirect to the login page.

$wp_sessions = WP_Session::get_instance();
if ( isset( $wp_sessions['id'] ) ) {
    return true;
}
wp_redirect( 'http://www.example.com/login/', 302 );
exit;

Hope you can help me out.

Regards,
TK

Add filter 'wp_session_expiration' doesn't work

Everything works great except the add_filter 'wp_session_expiration'. I want the session expired in 24 hours.

I have added it something like this:

function my_session_expiration(){ 
         return 60 * 60 * 24; 
} 
add_filter( 'wp_session_expiration', 'my_session_expiration' );

However, if I will edit this method 'set_expiration' and change to 24 hours expiration it works fine.

Can you please let me know your thoughts on this issue?

Thanks.

Avoid autoloading the "_wp_session_{$id}" options

Using "update_option" to initially add an option will call "add_option" with the autoload argument set to "yes". I do not think that all sessions should be autoloaded. It would be more performant to only look up a single option for each page load as opposed to all of the session options (I should note, however, that the autoloaded options are all loaded with a single MySQL query, so this change would lead to the same number of queries). I think if the data is not needed for every page load, it is fundamentally incorrect to load it for every page load.

To change this, you should check for the existence of the option before creating it. If it exists, use "update_option" to update the value. If it does not exist, use "add_option" to update the value and set "autoload", the 4th argument, to "no".

Version 2.0 Does Not Appear To Work

I updated this plugin to version 2.0 and values are no longer being stored correctly.

Here is my test code ( I've tried this on two different sites ):

function test_session_plugin(){
	$wp_session = WP_Session::get_instance();
	$wp_session['testing'] = 'test';

	echo '<pre>'; print_r( $wp_session ); echo '</pre>'; //@DEBUG
}
add_action( 'init', 'test_session_plugin' );

This is what the output of the $wp_session variable is:

WP_Session Object
(
    [session_id] => d9748edf3d29e6cd5814e973ed83d512
    [expires:protected] => 1512403822
    [exp_variant:protected] => 1512403462
    [container:protected] => t
    [dirty:protected] => 1
)

When I comment out the line that sets the session variable, I get the same output. It appears to be storing the data. It just stores it incorrectly.
The previous version of the plugin worked without issue.

wp_session_unset not clearing variables

This plugin is working very well for me, but there is one small issue I noticed. When using wp_session_unset(); it seems to unset the variables, but when you go to another page (that doesn't reassign them) the variables retain their previous values.

$wp_session = WP_Session::get_instance();
//Determine current page id (without loop)
$page_url = explode('?', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$page_id = url_to_postid($page_url[0]);

if ($page_id == 14) {
    $wp_session['MY_VARIABLE'] = 'MY_VALUE';
}
elseif ($page_url[0] == site_url().'/') {
    wp_session_unset();
}
$my_variable_instance = $wp_session['MY_VARIABLE'];

In the above example, going to a page with ID of 14 sets the variable to 'MY_VALUE', and going to the site url returns null for $my_variable_instance. However, if you then go to any other page, say ID of 15, $my_variable_instance returns it's previously assigned value of 'MY_VALUE'.

I've worked around this by manually unsetting the variable (instead of wp_session_unset() I'm using unset($wp_session['MY_VARIABLE']);)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.