0

I am building an EE plugin and need to store some information in a session.

How can I save and retrieve information from a session in an EE plugin?

Thanks

1

The EE Session cache is for "Flash" content on page load, so useful for storing temporary data which will get wiped per page refresh.

If you need it to store data via your templates, I'd highly recommend this add-on: http://devot-ee.com/add-ons/session-variables-plugin

Otherwise you just want to utilise PHP sessions, here's some functions from one of my add-ons:

//###   Get the Session variable (Array) for this class   ###
public function get_session() {
    $this->create_session();

    if (!empty($_SESSION[$this->class]))
        return $_SESSION[$this->class];
    else
        return false;
}//###   End of get_session function   ###

//###   Set the Session variable (Array) for this class   ###
public function set_session($value = "") {
    $this->create_session();

    if (is_array($value))
        $_SESSION[$this->class] = $value;
    else
        $_SESSION[$this->class] = "";
    return;
}//###   End of set_session function   ###

public function create_session() {
    //###   Set up cookie storage for use with or without the www   ###

    $this->sessionID = session_id();
    if ($this->sessionID == "" && !headers_sent()) {
        $URL = $this->EE->config->item('site_url', 1);

        if (strpos($URL, "www.") !== FALSE)
            $domain = substr($URL, strpos($URL, "www."));
        else
            $domain = $URL;

        if ($searchPos = strpos($domain, "//"))
            $domain = substr($domain, $searchPos+2);
        if ($searchPos = strpos($domain, "/"))
            $domain = substr($domain, 0, $searchPos);
        if ($searchPos = strpos($domain, ":"))
            $domain = substr($domain, 0, $searchPos);
        if (substr($domain, 0, 1) != '.')
            $domain = '.'.$domain;

        //session_set_cookie_params(0, '/', $domain, false, true);
        setcookie(session_name(), session_id(), 0, '/', $domain, 0);
        setcookie(session_name(), session_id(), 0, '/', $domain, 1);
        session_start();
    }
} //###   End of create_session function

You'll need to set $this->class in the class or construct. You could extend it so the set added it as array elements, and get had a parameter for which element of the array to retrieve.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.