1

I'm doing very secure and tight photo upload with multiple validations. All is set up. However I am stuck at limiting the incoming body size. I'm using a custom method to upload, images are usually between 0.5-5 MB, and I would like to force 5 MB as the limit. A custom method works as an encrypted JSON array passed with some parameters and a JSON field with image b64 string.

$size = (float)$_SERVER['CONTENT_LENGTH']/1024*1024;
if ($size > 5) {
    die('file too big');
}

This code does not exactly do what I'm looking for, because it waits until the entire body is received which makes this code useless. Is there a way to read the CONTENT_LENGTH header before or during uploading the POST body to drop it if necessary?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

1

I think it is better to solve this problem even before the file hits the backend server. On the proxy level, for nginx, you can use client_max_body_size

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sinan Ulker
  • 445
  • 8
  • 20
  • Is it possible to provide custom, json based response? static of course. –  Mar 16 '17 at 21:43
  • Well i don't know about json based responses but, you can use nginx's [error_page](http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page) directive to redirect user where you want for a special error code. Edit: Typo – Sinan Ulker Mar 16 '17 at 22:15
0

Firstly about your base64 image string: Note that it will be approximately 37% larger (source).

What does 2014 in /1024*2014; mean?

Here the PHP code which retrieves only headers without downloading:

<?php
    $head = array_change_key_case(get_headers("http://photojournal.jpl.nasa.gov/jpeg/PIA03239.jpg", TRUE));
    $filesize = $head['content-length']/1024/1024;
    if ($filesize > 30) {
        print("File is bigger than 30 MB and file size is:\n" . $filesize . ' MB');
    } else {
        print("File is smaller than 30 MB and file size is:\n" . $filesize . ' MB');
    }
?>

As a proof, the image link I entered has ~35 MB size which will take some time to download, but the code returns size in no time.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BladeMight
  • 2,670
  • 2
  • 21
  • 35
  • /1024*2014; - Typo. Corrected. According to your answer i'm looking for someting similar but when user execute php code on my server, then i need to do this. –  Mar 16 '17 at 20:50
  • @dansr23 Similar, huh? Here you go http://stackoverflow.com/questions/2602612/php-remote-file-size-without-downloading-file – BladeMight Mar 16 '17 at 20:54
  • But it does not apply for this case. I'm not looking for way to read header of remote file. I'm looking for way to read size of post body sent to this script. –  Mar 16 '17 at 20:59
  • @dansr23 OK I get it, then maybe this http://stackoverflow.com/questions/1361451/get-size-of-post-request-in-php (look at all answers) – BladeMight Mar 16 '17 at 21:09