master

laravel/framework

Last updated at: 29/12/2023 09:24

ValidatePostSize.php

TLDR

This file contains the ValidatePostSize middleware class, which is responsible for handling incoming requests and validating the size of POST data.

Methods

handle

This method is responsible for handling an incoming request. It checks if the size of the request's content exceeds the maximum size specified in the server configuration. If the content size is too large, it throws a PostTooLargeException. Otherwise, it proceeds to the next middleware in the pipeline.

getPostMaxSize

This method is a helper method used by the handle method. It determines the maximum post size specified in the server configuration. It converts the size value to bytes and returns it as an integer.

Classes

ValidatePostSize

The ValidatePostSize class is a middleware class that ensures the size of the POST data in the incoming request does not exceed the maximum size specified in the server configuration. If the size limit is exceeded, it throws a PostTooLargeException.

<?php

namespace Illuminate\Http\Middleware;

use Closure;
use Illuminate\Http\Exceptions\PostTooLargeException;

class ValidatePostSize
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     *
     * @throws \Illuminate\Http\Exceptions\PostTooLargeException
     */
    public function handle($request, Closure $next)
    {
        $max = $this->getPostMaxSize();

        if ($max > 0 && $request->server('CONTENT_LENGTH') > $max) {
            throw new PostTooLargeException;
        }

        return $next($request);
    }

    /**
     * Determine the server 'post_max_size' as bytes.
     *
     * @return int
     */
    protected function getPostMaxSize()
    {
        if (is_numeric($postMaxSize = ini_get('post_max_size'))) {
            return (int) $postMaxSize;
        }

        $metric = strtoupper(substr($postMaxSize, -1));

        $postMaxSize = (int) $postMaxSize;

        return match ($metric) {
            'K' => $postMaxSize * 1024,
            'M' => $postMaxSize * 1048576,
            'G' => $postMaxSize * 1073741824,
            default => $postMaxSize,
        };
    }
}