“Headers already sent” error on ChaCo servers

This is the error that’s clogging up the php-errors.log on both the local and live servers.

[09-Dec-2023 17:00:55 Europe/London] PHP Warning:  session_start(): Cannot start session when headers already sent in /home/chapelto/public_html/live/wp-content/themes/wfs2_child1/functions.php on line 62
[09-Dec-2023 17:00:55 Europe/London] Headers already sent in  on line 0

There’s a good overview at How to fix “Headers already sent” error in PHP and – clearly – it’s a problem with php sessions.

PHP sessions

Apparently WordPress no longer likes php sessions, as explained here and in WordPress Doesn’t Use PHP Sessions, and Neither Should You. And in the Site Health section of the Dashboard, one of the critical issues that is sometimes listed is ‘An active PHP session was detected’.

But it took a bit more googling to discover what the recommended replacement is.

Transients is the way to go

Here’s the WP official lowdown.

So we need to track down every occurrence of session_start() or $_SESSION. But first we need to test out the Transient API – maybe starting with the opening_message system.

In (eg:) subscriptions_template.php:

if($qmode == 'try' && $subscriptions_form_obj->get_complete()) { //v2.93
	$_SESSION["openingmessage"] = "Database record updated";
	header("Location: ".SELF_URL); 
	exit();
} 

In index.php:

if(isset($_SESSION["openingmessage"]) && $_SESSION["openingmessage"]) {
	echo("<div class='alert_message'>".$_SESSION["openingmessage"]."</div>");// gets faded out by child_specific.js
 	$_SESSION["openingmessage"] = '';
} 

In child_specific.js:

// fade out and remove any opening message
$('.alert_message').delay(1500).fadeOut(1000,function() {
	$(this).remove(); 
});

Sorted opening_message for:

  • chaco_proposal_plugin.php
  • subscriptions_template.php
  • ChaCo_Task_Groups.php
  • shortcodes.php
  • households_template.php
  • class-chaco_membership-public.php
  • class-chaco_seal-public.php
  • finishes-generic-single-post.php

$_SESSION removed from:

wf_forms.php – together with capcha.php
wf_validation.php
wf_dev_toolkit.php
functions.php

Seems to be all sorted now, with none of these errors in the php-errors.log.

Celebrated by starting a new log!