tags:

views:

691

answers:

5

Is there any way to get size of POST-request body in PHP?

A: 

My guess is, it's in the $_SERVER['CONTENT_LENGTH'].

And if you need that for error detection, peek into $_FILES['filename']['error'].

Michael Krelin - hacker
I'm uploading large files on server along with other fields. But if I abort it part of the request will be missing, so I need to compare actual size of request body with the value from Content-Length header to ensure the file uploading wasn't aborted.
Andrey M.
`$_SERVER['CONTENT_LENGTH']` of course contains the value from the header. I think it's PHP's responsibility to make sure it complies with the actual data being received. Maybe `$_FILES['file']['error']` has some hints for it?
Michael Krelin - hacker
If you're trying to detect failed file uploads, you should be doing it the way it's shown in my post, not counting bytes.
Keith Palmer
I have updated my answer to include reference to `$_FILES`. Thanks for confirmation, Keith.
Michael Krelin - hacker
A: 

I guess you are looking for $HTTP_RAW_POST_DATA

n1313
Hmm... But you don't need the data to know its size, do you?
Michael Krelin - hacker
Thanks, but $HTTP_RAW_POST_DATA is not available with enctype="multipart/form-data". I need to use multipart/form-data to send files.
Andrey M.
+1  A: 

If you're trying to figure out whether or not a file upload failed, you should be using the PHP file error handling as shown at the link below. This is the most reliable way to detect file upload errors:
http://us3.php.net/manual/en/features.file-upload.errors.php

If you need the size of a POST request without any file uploads, you should be able to do so with something like this:

$request = http_build_query($_POST);
$size = strlen($request);
Keith Palmer
otherwise if he 'just' wants size, you can get it for a file by using the $_FILES array => $_FILES['nameoffile']['size']
Jakub
A: 

This might work :

$bytesInPostRequestBody = strlen(file_get_contents('php://input'));
// This does not count the bytes of the request's headers on its body.
p4bl0
+1  A: 

As simple as:

$size = (int) $_SERVER['CONTENT_LENGTH'];

Note that $_SERVER['CONTENT_LENGTH'] is only set in HTTP Requests via POST method. This is the raw value of the Content-Length header. See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13

In the case of file uploads, if you want to get the total size of uploaded files, you should iterate over the $_FILE elements to sum each $file['size']. The exact total size does not match the raw Content-Length value due to the encoding overhead of the POST data.

Also note that for file errors, you should check the $file['error'] code of each $_FILES element. For example, partial uploads will return error UPLOAD_ERR_PARTIAL and empty uploads will return UPLOAD_ERR_NO_FILE. See file upload errors documentation in the PHP manual.

scoffey