Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

robgeorgeuk's avatar

Can you share some code to allow us to see this issue in action?

RichardUnderwood's avatar

@robgeorgeuk sure, what would be beneficial to see?

Home controller is just:

<?php namespace App\Http\Controllers;

use Session;

class HomeController extends Controller {

    /*
    |--------------------------------------------------------------------------
    | Home Controller
    |--------------------------------------------------------------------------
    |
    | This controller renders your application's "dashboard" for users that
    | are authenticated. Of course, you are free to change or remove the
    | controller as you wish. It is just here to get your app started!
    |
    */

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }

    /**
     * Show the application dashboard to the user.
     *
     * @return Response
     */
    public function index()
    {
        return view('home');
    }

}

and the method for a create view for an item goes like:

    public function create()
    {   
        $action = 'create';
        $job_type = 'Expression of Interest';
        return view('pages/expression-of-interest')->with( array('job_type' => $job_type, 'action' => $action) );
    }

And the form on pages/expression-of-interest opens with:

{!! Form::open( array('route' => 'expression-of-intetest.store', 'files' => true, 'id' => 'js-request-form') ) !!}

RichardUnderwood's avatar

@robgeorgeuk @bashy Another screenshot, the token in the session is the same as the one in the hidden input but submission still fails here with a token mismatch exception. This is really confusing now.

Screenshot

bashy's avatar

Does it redirect before reaching the final page or anything?

RichardUnderwood's avatar

@bashy Here's the method that handles storing the form data in the session.

    public function store()
    {
        //save the jobs to the session

        $full_request = Request::all();
        $requsts = Request::input('request');

        $count = 0;

        foreach($requsts as $request):

            //create the item array
            $this->arrangeData($full_request, $request, $item, $count);

            //push or create the session items array
            Session::push('items', $item);

            $count++;

            //clear arrays so no data is carried over to next iteration
            unset($item);
            unset($files);

        endforeach; 

        return Redirect::to('review');
        
    }
robgeorgeuk's avatar

@LindenWalsh All the bits you're showing us look fine but there must be something, somewhere in your app that is causing the issue. It's doubtful there is a server issue (as the problem exists on two servers) and doubtful it's a browser issue.

Personally I would try three things, you can choose which one you try first ;-)

  1. Create a new Laravel installation and add the minimum amount of code necessary to add and retrieve these items to/from the session. Assuming this works then gradually add in more parts of the app and test each step. If you manage to a build a really minimal example that still fails then you could publish the whole thing to GitHub (or somewhere) which would allow other to review it far more easily.

  2. Use XDebug to step through your code and find the parts that affect the session values and see if you can spot where things are going wrong.

  3. Try using Redis as your session driver. Honestly I'd be surprised if that fixed it but it's a quick and easy try!

Good luck!

RichardUnderwood's avatar

@robgeorgeuk Cheers! Unfortunately yeah it doesn't look like there's a quick fix for this. Have the coffee ready and might as well try to get this fixed before the long weekend! Thanks for your help and everyone else's! I'll post back once I get it sorted.

Cheers!

1 like
RichardUnderwood's avatar

@robgeorgeuk @bashy @sitesense

Working through debugging the problem I decided to quickly try making an ajax request to this route:

Route::get('debug', function() {
    $d = Config::get('session.lifetime');
    print $d;
});

Ajax call:

$.get( "/debug", function( data ) {
  console.log('session debug');
});

With that in place sessions work as expected. Now I just need to figure out why visiting any page without the app html works for creating a session that persists across requests.

My app.blade.php is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Title</title>

    <link href="{{ asset('/css/app.css') }}" rel="stylesheet">

    <!-- Fonts -->
    <link href='http://fonts.googleapis.com/css?family=Raleway:600,700,400,300' rel='stylesheet' type='text/css'>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body class="@yield('body-class', '')">

    <div class="animsition">

        <header class="main-header">
            <div class="container">
                <div class="brand-primary">
                    <a class="animsition-link" href="/"><img src="{{ asset('/images/brand-primary.png') }}" alt="Brand Nane" /></a>
                </div>
                <div class="brand-secondary pull-right">
                    <a class="animsition-link" href="/"><img src="{{ asset('/images/brand-secondary.png') }}" alt="Print Req" /></a>
                </div>
            </div>
        </header>

        @yield('content')

        <footer class="main_footer"> </footer>

    </div><!--/animsition-->

    <!-- Scripts -->
    <script src="{{ asset('/js/all.js') }}"></script>
</body>
</html>

and a small view content example:

@extends('app')

@section('body-class', 'home')@stop

@section('content')

    <div class="container">
        <h1>1. Please select the product you require</h1>

        <div class="items-wrap">

            <div class="row js-items-row">
                <div class="col-xs-3">
                    <div class="item">
                        <a class="animsition-link" href="folder-package-application/design-construction-folders"><img class="img-responsive item--thumb" src="{{ asset('/images/items/thumb-folder.png') }}" alt="Design and Construction Folder" /></a>
                        <a class="item--name js-item-name animsition-link" href="folder-package-application/design-construction-folders">Item 1</a>
                        <a class="btn btn-link btn-item-select animsition-link" href="folder-package-application/design-construction-folders">Select</a>
                    </div>
                </div><!--/col-->

                <div class="col-xs-3">
                    <div class="item">
                        <a class="animsition-link" href="folder-package-application/construction-package"><img class="img-responsive item--thumb" src="{{ asset('/images/items/thumb-folder.png') }}" alt="Design and Construction Folder" /></a>
                        <a class="item--name js-item-name animsition-link" href="folder-package-application/construction-package">Item 2</a>
                        <a class="btn btn-link btn-item-select animsition-link" href="folder-package-application/construction-package">Select</a>
                    </div>
                </div><!--/col-->

        </div><!--/item-wrap-->

    </div><!--/container-->

@endsection

Maybe there's something in the view that is messing it up? I can't see anything but it's where I am with narrowing it down at the moment.

sitesense's avatar

@LindenWalsh does the session regenerate just through normal navigation or refreshing a page - i.e. no form submits?

If so, create a very basic route to a basic controller and basic view file with no layout (no javascripts or anything). On this occasion, use the same middleware as your normal routes.

See if your session persists normally using that route.

If it works, it must be something in your regular controllers or views/layouts.

If it doesn't, cut out any middleware and see if that works.

If it works without the middleware, then... well I guess you see what I'm saying :)

Hopefully that will give us some clues.

By the way, I was wondering about this:

public function store()
    {
        //save the jobs to the session

        $full_request = Request::all();
        $requsts = Request::input('request');

        $count = 0;

        foreach($requsts as $request):

            //create the item array
            $this->arrangeData($full_request, $request, $item, $count);

            //push or create the session items array
            Session::push('items', $item);

            $count++;

            //clear arrays so no data is carried over to next iteration
            unset($item);
            unset($files);

        endforeach; 

        return Redirect::to('review');
        
    }

$this->arrangeData($full_request, $request, $item, $count); where does $item receive its value?

And what does arrangeData do?

I thought perhaps the session might be corrupted in some way, causing it to regenerate, but if it happens when store isn't even called then I'm barking up the wrong tree.

Good luck!

Dinner231's avatar

Session ID on load is session ID is currently fbd69d01d511a7be382799dca7279a86 (or a variant)

the session Id is always blank before session_start() is called and it is always a new session_id()

It does this in all browsers and I have checked to make sure cookies are turned on.

the session save path is given as /tmp. I am not sure exactly where that is, but looking through my root and all other directories, I can't find a session file (assuming it would look something like sess_fbd69d01d511a7be382799dca7279a86).

So I am thinking there is something going on with the save path, but am too new at this to know for sure, and the server admins are being fairly unhelpful. What should my next steps at diagnosing the issue be? The server is running 5.3.22.

http://www.custodiasamsung.com http://www.custodiasamsung.com/category-custodie-cover-samsung-galaxy-s6-7.html

RichardUnderwood's avatar

@sitesense Sorry about the delay in replying, I had to use the quick fix for now and move the project on and try to debug the real cause later, not ideal but deadlines and all that are looming.

Yeah arrangeData() is just called in the store method and doesn't interact directly with the session. It just takes the request data from a form and oragnises it by the type of job that was requested, sets the job(s)'s properties and saves uploaded files to S3. What's returned from that method is stored in the session but the session breaks before these methods can be called. I think there's something in the view that's breaking it but I haven't had much time to investigate it. Will post an update when I figure it out.

Thanks for your help!

sitesense's avatar

@LindenWalsh did you manage to sort out this problem?

If not, something came into my head when I was looking at the way tokens are matched.

protected function tokensMatch($request)
{
    $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');

    if ( ! $token && $header = $request->header('X-XSRF-TOKEN'))
    {
        $token = $this->encrypter->decrypt($header);
    }

    return StringUtils::equals($request->session()->token(), $token);
}

So if $request->input('_token') or $request->header('X-CSRF-TOKEN') are not found, then we look to see if $request->header('X-XSRF-TOKEN') exists and use that instead.

$request->header('X-XSRF-TOKEN') is supposed to be an encrypted token so it is first decrypted and then checked to see that it matches the session token.

I wondered if somehow you were setting the XSRF-TOKEN in your headers using an un-encrypted token (I can see from your session config that encryption isn't enabled) - and when that is decrypted it would no longer match the session token.

Looking at one of your screenshots, I noticed XSRF-TOKEN in the cookies here:

XSRF-TOKEN

Maybe something to look at?

RichardUnderwood's avatar

@sitesense Nope still using the hacky workaround but hoping to get some time to investigate the cause more in the next couple of days.

Cheers for the lead though, really appreciate it!

surfer190's avatar

@LindenWalsh I think your issue is an error in the view templating.

Basically the problem was that the session cookie was not set correctly due to template errors.

In your case you should remove the @endsection for the @section('content'). Change that to @stop.

1 like
markus3295's avatar

I was having the same issue. The token is updated every time then reload the page.

Laravel version is Laravel Framework 5.7.15.

Solution: I removed this Middleware from $middlewareGroups (web) in \App\Http\Kernel:

\App\Http\Middleware\EncryptCookies::class

As i understand it, the problem is with the encryption. But what the matter is, i don't understand.

However, the sessions began to work correctly. The token is not updated on every hit.

dcranmer's avatar

@surfer190 Changing @endesection to @stop seems to work for me, too. Thank you, but what's the difference between the two, and why does @stop work? Why is using @endsection a templating error? (I'm still on Laravel 5.5)

Edit: After replacing @endsection with @stop, I then reverted back to @endsection, and it still works. Makes me think there was a bad character or something else wrong in the template file itself. From what I can tell, both directives compile to $__env->stopSection()

Previous

Please or to participate in this conversation.