Laravel 5 - session doesn't work - php

Here's config/session.php:
return [
'driver' => 'file',
'files' => storage_path().'/framework/sessions',
];
My storage/framework/sessions have 755 permissions.
When I put these 2 line in my controller
Session::set('aa', 'bb');
dd(Session::get('aa'));
I receive expected "bb" output. But if I comment first line:
// Session::set('aa', 'bb');
dd(Session::get('aa'));
and refresh page, I still expecting "bb" but getting null.
Also, storage/framework/sessions is empty.
What should I do to make Session working?

Laravel 5 handles sessions via a middleware class called StartSession. More importantly, this middleware is a TerminableMiddleware and the code that actually saves the data (in your case to the session file) is located in the terminate method, which is run at the end of the request lifecycle:
public function terminate($request, $response)
{
if ($this->sessionHandled && $this->sessionConfigured() && ! $this->usingCookieSessions())
{
$this->manager->driver()->save();
}
}
When calling dd(Session::get('aa')); the request is being interrupted before the terminate method of the middleware can be called.
Funnily enough, the Laravel Middleware Documentation actually explains Terminable Middleware logic by giving the Laravel StartSession middleware as an example:
For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser.
That being said, try using var_dump() instead of using dd().

With laravel 5.*, you must change the kernel file like bellow:
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
'throttle:60,1',
'bindings',
],
then go to storage/framework/session folder and change the permission to 755 if it has another amount, then delete all files in your storage/framework/session path, use your code again to put something in a session, watch the storage/framework/session folder.
If your session work you can see the weird long file that belong to session right now, and you are done!
If your problem is not yet solved, go to config/session and change:
'driver' => env('SESSION_DRIVER', 'file')
to another predefined amount like:
'driver' => env('SESSION_DRIVER', 'array'),
or even
'driver' => env('SESSION_DRIVER', 'database'),
and finally if you have an empty folder of storage/framework/session, you still have a problem for sure !!!

if you're use api route , you might have this problem with your session and most of the time sessions return null ,
try to use web route for this

Related

Laravel - Working with sessions between controllers

I need to show some values in all app, and sometimes I need to use these values between controllers.
I was trying to use Session, but I maybe it is not the answer to that, because if I am not wrong, Laravel store the session data temporarily in memory and only after everything has been executed, will it dump the session data into storage (file, cookie, redis, whatever).
So for example, I have a controller like that:
class GiftController extends Controller
{
public function dashboard(){
$token = (Session::has('token')) ? Session::get('token') : NULL;
if (is_null($token)){
return view('test.erro', ['message' => 'no session!']);
}else{
return view('test.ok', ['message' => $token]);
}
}
public function setsession(){
Session::put('token','xxxxxxxxxxxx');
return redirect('test/dashboard');
}
}
In this case, if I do an echo on Session::get('token') into the setsession(), is showing the value, but when it goes to the dashboard(), the session shows nothing.
What I am doing wrong?
or What is the better Idea to use instead off session?
I am using the Laravel Framework 5.8.37
I found the solution but I got it with the markskayff help.
He told me to Check my .env file, and he was right! It was a different SESSION_DRIVER value from config/session.php
In config/session.php was 'driver' => env ('SESSION_DRIVER', 'file')
Despite not having .env file but app.yaml since I am doing this project in GCP app engine, the session in this file was SESSION_DRIVER: cookie.
So I changed in config / session.php the line 'driver' => env ('SESSION_DRIVER', 'file') to 'driver' => env ('SESSION_DRIVER', 'cookie').
And now it is working!

Why have I to use session_start() to make session persist in Laravel 5.7.28

I am trying to create a session in PagesController > designQuote function. The Laravel call to session works but the session does not persist. Here is the code.
Session::push('design_quote_uploads.files', ["Hello"]);
print_r(Session::all());
This works first time but when I comment out the first line design_quote_uploads does not exist in the session vars in the next page load.
The config/Session.php settings is
'driver' => env('SESSION_DRIVER', 'file'),
After reading doc and another answer here I checked the Routes and Middleware and it looks like this:
In the web.php the call is:
Route::any('design-quote', 'PageController#designQuote');
The middlewareGroups in Kernel.php:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
If I place session_start(); at the top of designQuote method the session persists. Do I have to keep it there?
Edit: (I swear) Placing session_start() worked yesterday but it is not working today :(
Also the session file at storage/framework/sessions is updated fine every time. I.e. It has data when it is written and misses data when I refresh the page.
I don't know what is missing out there. I checked another answer but I didn't understand it fully. It seems like quite old as well. Any help is appreciate.

Laravel 5.4 session token changes on every request

I have a project on Laravel 5.4 and PostgreSQL. At each page request, the session is renewed with a new _token key and a new cookie. As a consequence, either authentication nor flash sessions message are not working.
Already tried :
Changed laravels' cookie name
Played with $domain variable in session.php, tried null, http://localhost:8000 and http://localhost
Switched from file to array and redis
Played with encrypted => false/true and all others booleans fields
Checking storage/sessions folder permissions (all set to 777)
In my routes.php file, replaced middleware by middlewareGroups
The RouteServiceProvider.php :
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
(there is no web.php/api.php, etc... PHP files, the developper remapped all these files into routes.php).
Your domain is invalid. You need to look at config.session.domain and config.session.path.
Your browser will not store cookies for a domain without a dot. E.g. localhost. A simple fix is to add 'localhost.com' to your hosts file as 127.0.0.1.
Then you can use for example: localhost.com:8080

Laravel - Session returns null

I'm using sessions for the first time in Laravel and I'm trying to do a multiple step form, so I thought using sessions would be a smart move. however the following code returns a null value, what am I doing wrong?
$user_information = [
"name" => $request->name,
"email" => $request->email,
"remember_token" => $request->_token,
"password" => bcrypt($request->password),
"role_id" => 3
];
session('user_signup', $user_information);
dd(session('user_signup'));
In your controller you can save variable into session like
session()->put('user_signup',$user_information);
For checking your session variable in controller
session()->has('user_signup','default value');
For deleting your session variable in controller
session()->forget('user_signup');
For checking your session variable if it exists in blade and printing it out
#if(session()->has('user_signup'))
session()->get('user_signup')
#endif
I have tested this already and struggling along then I realized that I should never use dd() (the dump and die method) after using the session() because your are blocking the system from writing on the session() cookie file.
I'm not really sure about that but it works for me .. let me know if this is True.
Try this
session(['user_signup'=> $user_information]);
or
session()->put('user_signup',$user_information);
and you can check session by logging it
Log::info(Session::get('user_signup'));
check your log file it should be there.
Laravel docs link - https://laravel.com/docs/5.4/session#storing-data
first : you put something in a session
second : check the storage/framework/session folder , if your session work fine you can see your session data in a session folder now.
if you save a session and session folder is still empty :
first change the 'driver' => env('SESSION_DRIVER', 'file')
to 'driver' => env('SESSION_DRIVER', 'array') and 'driver' => env('SESSION_DRIVER', 'database')
second set the storage/framework/session permission to 755
and finally go to your kernel file and add bellow code in 'api'
'api' => [
//add this bellow two line
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
'throttle:60,1',
'bindings',
],
then check your session folder again and if you put something in any session you should now see them in this folder, you can delete files in session folder, use the session again to save something in it , going back to session folder and see the session folder is not empty anymore , and you're done, image of the session folder

Laravel 5 session not persisting after user is logged in

I'm having an interesting issue with Laravel 5.
After logging in a user, the logged in status is not persisted across pages. Clearly it has something to do with Session::.
The way I'm logging in a user is pretty straight-forward:
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']],
isset($data['remember_me']) ? TRUE : FALSE))
{
return redirect()->intended('/');
}
A simple print_r(Session::all()); gives me the following if the user is NOT logged in:
Array
(
[_token] => wV8o75lZnCZ0f6CMMQgdBBM2AxSYjtWisAXx6TgZ
[flash] => Array
(
[old] => Array
(
)
[new] => Array
(
)
)
[_previous] => Array
(
[url] => http://localhost/public
)
)
After the user is logged in an redirected to / the array looks like this:
Array
(
[_token] => wV8o75lZnCZ0f6CMMQgdBBM2AxSYjtWisAXx6TgZ
[flash] => Array
(
[old] => Array
(
)
[new] => Array
(
)
)
[_previous] => Array
(
[url] => http://localhost/public/
)
[login_82e5d2c56bdd0811318f0cf078b78bfc] => 2
)
However, after any action that will lead to a page refresh or a redirect, the session status is lost.
My config/session.php file looks like so:
<?php
return [
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 120,
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => null,
'table' => 'sessions',
'lottery' => [2, 100],
'cookie' => 'laravel_session',
'path' => '/',
'domain' => null,
'secure' => false,
];
The locally stored file for the session can be written and read.
I've tried using database drive instead of file. Same thing happens the [login_xx] => 2 key/value is lost and I'm logged out.
Since the Session:: is not completely reset I'm suspecting that I'm not logging in the user properly or simply doing something that I shouldn't be doing somewhere.
I faced similar issue, I simply called:
Session::save();
after any add/update/delete to Session storage. So it looked like:
$id = Input::get('id');
Session::forget('cart.' .$id);
Session::save();
I had the same issue. Once I removed the various combinations of dd() and print_r() I was using to dump responses for testing purposes and allowed the method to complete and fully render the view, the issue went away and sessions persisted.
I solved changing
'cookie' => 'laravel_session',
to
'cookie' => 'myapp_session',
according to laravel the name of the cookie affects every driver
I'm not familiar with Laravel, but on CodeIgniter I save user session in CI's Session Class and Laravel has one too.
I suggest to use the build-in session which is more persistent than default $_SESSION - probably it saves user data in database and on each page refresh/change the session is populated again from DB.
When user authenticates, just save its session data like this:
Session::put('userData', 'value');
...where value could be just a boolean value or an entire object that holds user specific data.
On each page load, get user data from session:
$user = Session::get('userData');
if($user->id) echo 'user is logged-in'; //or if($user) - depends on what you store in 'userData' key
else echo 'guest only privilegies';
EDIT:
I see that you use the Auth Class. My answer is mostly for manual login of the user and it works.
I think that the Auth Class should be doing this by default, but probably you're missing some configuration or there's a bug.
Here's a possible solution (Laravel 4, but it worths a try): http://laravel.io/forum/11-11-2014-authcheck-always-returning-false
Update:
As of this you should try to change the driver value from
'driver' => env('SESSION_DRIVER', 'file')
to
'driver' => 'file'
...also on Laravel's docs you can see that the driver has to be defined like that.
First, make sure you don't have some sort of a before filter, middleware, or route group that is causing them to be logged out. At least temporarily, search for any Auth::logout() and comment it out. I have seen this be the problem more than once.
Second, you look like you're doing this call correctly. The third parameter is $login : bool and it defaults to true. This is not your problem, but please change your TRUE and FALSE to true and false to meet with PSR-1/2 standards.
I would have advised that you try another driver, but you have done that and have the same result. This leads me to think that you have some sort of earlier code that is misdirecting to a logout().
You need to make sure of 2 things if you are using default laravel's file session which you can check if you are using in session.php file.
The session directory ie storage/framework/session/ is writable.
The routes for logging in maybe (/login) and for checking authentication (maybe /dashboard) are all within the group web
ie.
Route::group(['middleware' => ['web']], function () {
Route::get('/home/login', ['as' => 'login', 'uses' => 'HomeController#getLogin']);
Route::post('/home/login', ['as' => 'login', 'uses' => 'HomeController#postLogin']);
Route::get('/home/dashboard', ['as' => 'home', 'uses' => 'HomeController#getDashboard']);
}
This worked for me in Laravel 5.
I had this problem to and i solve this way.
After Auth::attemp or Auth::login() dont use echo, var_dump or dd() i dont know why but those prevent to keep the session in the browser.
And now is working
public function testLogin(Request $request, $id){
$user = Account::find($id);
Auth::login($user);
}
Don't forget to save like session()->save() or Session::save()
I have faced the same issues after the user logged in the session is not persistent.
So i found the solution for this.
just change one line in config/session.php file
Change in this code
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
)
To:
'cookie' => env(
'local_cookies',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
then clear the caches. it will fix the issue :)
correctedHum... Ensure your machine is setted with good date and hour, and equally the other machines on the network who working with.
For exemple in Debian system:
In the command prompt, hit date (you will see the date), if it's not correct follow these instructions:
apt-get install ntp
service ntp start
date (normally the date and hour are corrected)
Use "cookie" driver instead of "file" of session.php (config\session.php\driver). I had a problem with login using "Auth::loginUsingId()" api instead of "Auth::attempt()" api, it destroyed the session for another request.
Make sure that the target route also uses the middleware StartSession.
In my "fresh" installation of Laravel 5.2 the "web" middleware group uses it, but the root path (/), which also happens to be the default $redirectTo after login, was outside of it. Huge loss of time.
I had a similar problem and I have fixed it by changing the Session Driver from
SESSION_DRIVER=database
to
SESSION_DRIVER=file
In my case I had to change the domain setting in the app/config/sessions.php file. I had a different domain written there instead of the one that I was using and naturally it didn't work. Though I don't understand why the framework went ahead and created the session files each time I was reloading the page.
I had the same issue, but it has been fixed now.
It's because of the conflict between sessions in your machine and in your localhost domain. To solve the problem:
First of all check your config/session.php file and check this:
'domain' => null,
after that clear your cookies:
on Firefox, right click -> view page info -> Security -> View Cookies -> Remove all
i had the same problem in laravel 5.4, the solution for me was:
In the file /app/Http/Kernel.php, was commented middleware AuthenticateSession by default.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
//\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
Only uncommented this line and the session work fine in all routes
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
If you are using loginUsingId() method you should set 'remember' flag to true.
So, instead of doing:
loginUsingId(1);
You should do
loginUsingId(1, true);
See docs
You might wanna check public/index.php, see if there are codes before the Laravel codes. After I remove those codes, I can login just fine.
<?php
echo 'hello';
?>
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* #package Laravel
* #author Taylor Otwell <taylor#laravel.com>
*/
I seems, someone "messed" with my sites, and index.php is the main target for malicious codes
Just add session start and authenticate middleware to global middleware in kernel.php file
just check then cookie allow false
'secure' => env('SESSION_SECURE_COOKIE', false)
In my case I put it as true insted of true, then I changed its into
false
I am faced this problem when dealing with the oracle database, and by searching and debugging it is solving by change the protected $primaryKey = "name in lowercase"
public $incrementing = false;

Categories