0

I wanted to make a persistent session for the user using a class, but it seems that I can't make it work. Currently, I have this:

<?php
class Session {
    private $sessionId = NULL;

    public function __construct() {
        session_start();
        if($this->sessionId === NULL)
            $this->sessionId = session_id();
        return $this->sessionId;
    }

    public function getSessionValue($field) {
        return $_SESSION[$field];
    }

    public function setSessionValue($field, $data) {
        $_SESSION[$field] = $data;
    }

    public function removeSessionValue($field) {
        unset($_SESSION[$field]);
    }

    public function destroySession() {
        $this->sessionId = NULL;
        session_destroy();
    }

    public function __toString() {
        return $this->sessionId;
    }
}
?>

But it happens that when I redirect the user to another domanin so he can make a payment, he loses its session when he's back to my website. Currently, I save some data with setSessionValue('paymentid', 1) method from this class, redirect using javascript and, when it comes back, I have this code to check if he's got a session value:

$session = new Session();
if($session->getSessionValue('paymentid') !== null) {
// Do something here
}

Which returns me an empty paymentid. The strange thing is that sometimes it works, but it doesn't all the time, so... What could be wrong with this?

Xabi
  • 159
  • 1
  • 3
  • 13
  • 1
    php start a session => php send you a cookie with the sessid => if the "other domain" is just a sub-domain, then you need to be sure that the cookie has been stored with the right domain attribute. Be aware that cookie with domain=siteA.com will not be available for siteB.com – Federkun Dec 04 '16 at 12:20
  • https://stackoverflow.com/questions/17242346/php-session-lost-after-redirect?rq=1 – Charlotte Dunois Dec 04 '16 at 12:25

1 Answers1

0

Double check your code that moves user between pages. You may be inadvertently reseting id value in your session vars. I find it helpful to do var_dump $_SESSION on my pages to see what's happening to my vars. As to why it works sometime, it may be for example that code that returns user from cancelled transaction is different from a successful one. Look at the code that leaves the id var intact since that's the one you want to apply elsewhere.

  • The code doesn't rewrite that in any moment. I will put a print_r for logging the $_SESSION before and after calling the payment url, but it's strange as it happens rarely and only to some people, which I don't understand since it's a server based session – Xabi Dec 04 '16 at 13:01