0

I'm building a web-application with Laravel with a file uploader in ajax.

I would like handle in PHP when the file exceeds the UPLOAD_MAX_SIZE limit.

Currently, I am adding this to /app/exception/Handler.php

public function render($request, Throwable $e): Response {
    if ($e instanceof PostTooLargeException) {
        return response()->json([
            'error' => 'Il file supera le dimensioni massime consentite. ' . ini_get("upload_max_filesize"),
        ], 422);
    }

    return parent::render($request, $e);
}

The response that I receive add two extra rows:

<br />
<b>Warning</b>:  POST Content-Length of 10087828 bytes exceeds the limit of 8388608 bytes       in <b>Unknown</b> on line <b>0</b><br />
{"error":"Il file supera le dimensioni massime consentite. 2M"}

I tried with APP_DEBUG set to false, and error_reporting(0) without success. How can return only the json?

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
cesare
  • 2,098
  • 19
  • 29
  • 2
    That warning is generated by PHP itself, it has nothing to do with laravel. You need to modify the relevant PHP configuration options, https://stackoverflow.com/a/11719522/1427878 – CBroe Apr 26 '23 at 10:59
  • @CBroe I do not want to increase the maximum value, but I want to handle the error. – cesare Apr 26 '23 at 11:03
  • 2
    But you _can't_, because PHP parses the request body and performs this check, before your own code even runs. Your options here are to either set the limit higher, or to disable all warnings via your error_reporting setting. – CBroe Apr 26 '23 at 11:15
  • 4
    You should increase the maximum value in your php configuration and then you can validate the file size using Laravel to prevent larger uploads. See this guide https://laraveldaily.com/post/validate-max-file-size-in-laravel-php-and-web-server – Coola Apr 26 '23 at 13:15
  • 1
    Just in case if you did not understand the comments, PHP will detect that you have excedeed the limit, and it will automatically print the error, it has nothing to do with Laravel, it is PHP (the core language itself) telling you about this warning (not error). 2 solutions: either mute this warning by ignoring printing warnings or just don't print anything (mute all errors and warnings) or give a bigger value and handle it yourself (always check the size of the uploaded file) and then print your error hidding this one – matiaslauriti Apr 26 '23 at 20:39

0 Answers0