Skip to content
Advertisement

How to use session in wordpress in plugin development

I am new to write a plugin ..I am having a testplugin.php file and a ajax.php file ..

My code in testplugin.php is

global $session;

print_r($abc); //$abc is array of my data ..

$session['arrayImg']=$abc; //saving data in session 

echo  $session['arrayImg']; //displayin "Array"

And my ajax.php consists of following code

global $session;

$abc = $session['arrayImg'];

print_r ("abs== ".$abc); //displayin "abs== Array"

And if use session_start();

I get following error

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent 

I just want to send array of data from one file of my plugin to another file …

Advertisement

Answer

Add following on your plugin or themes functions.php file

function wpse16119876_init_session() {
    if ( ! session_id() ) {
        session_start();
    }
}
// Start session on init hook.
add_action( 'init', 'wpse16119876_init_session' );

Next, to add data in SESSION

// If session has started, this data will be stored.
$_SESSION['arrayImg'] = $abc;

To get the data on ajax hooked function –

// handle the ajax request
function wpse16119876_handle_ajax_request() {
    if ( ! session_id() ) {
        session_start();
    }

    if ( array_key_exists( 'arrayImg', $_SESSION ) ) {
        $abc = $_SESSION['arrayImg'];
    } else {
        $abc = 'NOT IN SESSION DATA';
    }

    // Do something with $abc
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement