Search code examples
phplaravelcookiessession-cookiessetcookie

Cookies are not set in Laravel 5.3


I had Laravel on VPS ubuntu serving by Nginx and it worked correctly there. PHP was php-fpm7.0

Now I transferred it to a CPanel hosting and there the problem starts. It is using Cloudflare now and also in the past.

Laravel version: 5.3.13

PHP version: tested 5.6, 7.0, 7.1, 7.2

I get TokenMismatch error because no cookies and sessions are set.

.env contains:

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

config/session.php:

<?php
return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'store' => null,
    'lottery' => [2, 100],
    'cookie' => 'k_session',
    'path' => '/',
    'domain' => env('SESSION_DOMAIN', null),
    'secure' => false,
    'http_only' => true,
];

storage/framework/sessions chmod is 777 and I see after every request a file is created there. But nothing is sent to the browser.

I also tried Cookie::make(...) and session(['a' => 'b']) but still get nothing in browser headers. There are just cloudflare headers there.

I have also tested different SESSION_DOMAIN s. http://example.com, https://example.com, example.com, null, and none them worked. (Some pages are in http and some in https and none them send cookies)

Tip: I placed session_start(); in index.php file and I could set session using $_SESSION[] in the script but I know laravel has its own session driver and it's not the solution.


Solution

  • I finally solved this very small problem that caused it.

    I imported all files to my IDE. It took a lot of time and I finally searched for \s<\?php regex in all files. Then I found a line break in config/app.php file. There should not be anything echoed before sending headers.