Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use session in wordpress in plugin development

Tags:

php

wordpress

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

like image 231
Vaibs_Cool Avatar asked Apr 20 '13 09:04

Vaibs_Cool


People also ask

How do we use session?

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.

What is session explain with example the use of session?

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.

How do I use sessions in WordPress?

Starting A PHP Session In a standard PHP application, a session would be started using the session_start function at the very top of the PHP script. This may tempt you to open the header. php file in your WordPress theme and add something like the following to begin using sessions.


1 Answers

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 } 
like image 183
Shazzad Avatar answered Sep 23 '22 02:09

Shazzad