user4308245
user4308245

Reputation:

Read request header before reading entire body of POST request in PHP

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?

Upvotes: 1

Views: 345

Answers (2)

Sinan Ulker
Sinan Ulker

Reputation: 485

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

Upvotes: 1

BladeMight
BladeMight

Reputation: 2810

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.

Upvotes: 0

Related Questions