Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

php - 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 ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...