Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel sessions not available in native PHP?

Tags:

php

laravel

New to Laravel and having some problems with Sessions. Specifically, reading session data from a PHP file outside of Laravel.

For example, let's say I set the session variable like so: Session::put('isAuthorized', 'yes') - I can retrieve this just fine in the Laravel context with Session::get('isAuthorized') but the following PHP will not retrieve this session key -

<?php
session_start();
echo $_SESSION['isAuthorized'];
?>

returns

Notice: Undefined index: isAuthorized in C:\xampp\htdocs\session.php on line 3

I have tried setting the Laravel session driver to both the default cookie and file modes, same result.

like image 843
NightMICU Avatar asked Dec 04 '22 12:12

NightMICU


1 Answers

You could also write a session adapter, so the $_SESSION variable will be an instance of it:

<?php 
class SessionAdapter implements \ArrayAccess {

  public function offsetExists($offset) {
      return Session::has($offset);
  }

  public function offsetGet($offset) {
      return Session::get($offset);
  }

  public function offsetSet($offset, $value) {
      return Session::put($offset, $value);
  }

  public function offsetUnset($offset) {
      return Session::forget($offset);
  }

}

And then somewhere in your code:

<?php 
$_SESSION = new SessionAdapter();
// or
$GLOBALS['_SESSION'] = new SessionAdapter();

This way native PHP session and Laravel session will be "the same".

like image 196
itsjavi Avatar answered Dec 08 '22 15:12

itsjavi