[ad_1]
I am running WordPress (with Elementor Pro theme).
Since I added my custom form via shortcodes I have had this error in the Tools/Site Health:
An active PHP session was detected
A PHP session was created by a session_start() function call. This interferes with REST > API and loopback requests. The session should be closed by session_write_close() before > making any HTTP requests.
and
The REST API encountered an error The REST API is one way WordPress,
and other applications, communicate with the server. One example is
the block editor screen, which relies on this to display, and save,
your posts and pages. The REST API request failed due to an error.
> Error: cURL error 28: Operation timed out after 10000 milliseconds
with 0 bytes received (http_request_failed)
My shortcode is placed inside a file that is included in wp-content/themes/child-theme/functions.php
The file looks something like this:
<?php
session_start();
function form_shortcode_function() {
outputForm(); // output form and store form Object in $_SESSION
outputResults(); // output user results if there are any, also stored in $_SESSION
}
add_shortcode(‘custom_form’, ‘form_shortcode_function’);
// session_write_close(); // disabled or else $_SESSION data not written
The shortcode is added via the Elementor Editor as a shortcode block on a page.
I’m not sure it’s relevant but I use this script to make the POST request for the form:
function submitForm(event) {
event.preventDefault();
var data = new FormData(event.target);
var request = new XMLHttpRequest();
request.open("POST", event.target.getAttribute("action"), true);
request.send(data);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
document.open();
document.write(request.responseText);
document.close();
}
}
return false;
}
In this scenario when I POST the form to the server the script that is called access $_SESSION
and everything works as expected, data is present, and everything runs normal.
Except the WordPress Site Health.
After implementing the suggested solution and putting session_write_close()
at the bottom of the shortcode script writing data to $_SESSION
no longer works.
Stuff that is supposed to be set in $_SESSION
when outputForm()
runs is no longer accessible in the POST script and does not persist across requests.
I tested an independent script on my webserver:
<?php
session_start();
if ($_SESSION['test'] === 'set') {
++$_SESSION['counter'];
echo('session is set && counter=".$_SESSION["counter']);
} else {
$_SESSION['counter'] = 0;
$_SESSION['test'] = 'set';
}
session_write_close();
This behaves as expected and $_SESSION
is written to and persists across requests.
However I can not get this to work inside a WordPress shortcode.
I explored some ways of using WordPress methods add_action()
and do_action()
to initialize session_start()
and session_write_close()
at different points during runtime but without success.
[ad_2]