Skip to content

Instantly share code, notes, and snippets.

@xnau
Created March 17, 2024 01:05
Show Gist options
  • Save xnau/21cb290bc8f0885e8b770bac9db434f4 to your computer and use it in GitHub Desktop.
Save xnau/21cb290bc8f0885e8b770bac9db434f4 to your computer and use it in GitHub Desktop.
WordPress MU plugin for initializing a php session early in the load cycle
<?php
/*
* Plugin Name: Participants Database Session initializer
* Plugin URI: https://wordpress.org/plugins/participants-database/
* Description: Attempts to initate a php session before headers are sent
* Author: xnau webdesign
* Version: 0.1
* Author URI: http://xnau.com
*/
class PDb_Session_Init {
public function __construct()
{
if ( ! headers_sent() && session_status() !== PHP_SESSION_ACTIVE )
{
$this->start();
}
}
private function start()
{
$started_here = false;
if ( session_start() )
{
$started_here = true;
}
$phpcookie = ini_get( 'session.name' );
if ( empty( $phpcookie ) )
{
$phpcookie = 'PHPSESSID';
}
$sessid = session_id();
setcookie( $phpcookie, $sessid, 0, '/' );
if ( $started_here )
{
session_write_close();
}
}
}
new PDb_Session_Init();
@xnau
Copy link
Author

xnau commented Mar 17, 2024

On some WordPress installs, php sessions can't be started by a regular plugin because other plugins or a theme has sent out the php headers, preventing a session from getting started. This is because starting a session requires adding info to the header, but it can't do that after the headers have been sent.

This MU plugin attempts to avoid this problem by loading and activating the session before any other plugins or the theme can be loaded.

This should be installed in the mu-plugins directory of your WordPress.

  1. Download and unzip
  2. Use FTP or File Manager to upload the php file to wp-content/mu-plugins/
  3. Load a Participants Database page to make sure it's all working
  4. If you get a blank screen (very unlikely), go back to your FTP or File Manager and delete the plugin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment