Last Updated: February 25, 2016
·
1.214K
· buildcomplete

Adding a filter in laravel to check post size

Sometimes people upload more data than the server is configured to support.
this gives problems on many levels, but in laravel,

When they do this, Laravels Standard Cross site validation filter fails to pass. it makes sence since php drops all post data when trying to post more data then the server is configured to receive.

To provide a meaningfull error I created a filter to detect this:

Route::filter('postsize', function()
{
    if (isset($_SERVER["CONTENT_LENGTH"])
        && ($_SERVER["CONTENT_LENGTH"]>((int)ini_get('post_max_size')*1024*1024)))
    {
        throw new PostSizeExceededException();
    }
});

In my route i added the filter before the csrf filter

Route::post('/update/{step}', array(
    'before' => 'postsize|csrf|auth',
    'uses' => 'myController@postDashboardStep));

In start/Globals i added a error handler showing my custom view and logging the problem.

App::error(function(PostSizeExceededException $e)
{
    $errorData = Functions::CreateCommonError(413);
    Log::error('PostSizeExceededException', $errorData);
    return Response::view('errors.post_size_exceeded', $errorData, 413);
});

post size exception i placed in the Models folder:

class PostSizeExceededException extends Exception 
{
    public $validator = null;
}

and now I can in a nice way log the problem and show a custom message describing the problem