As far as I know there is no way to check if the size of received content matches the value of the Content-Length
header when using multipart/form-data
as Content-Type
, because you cannot get hold of the raw content.
1) If you can change Content-Type
(to application/x-www-form-urlencoded
for example) you can read php://input
, which will contain the raw content of the request. The size of php://input
should match Content-Length
(assuming the value of Content-Length
is correct). If there's a match, you can still use $_POST
to get the processed content (regular post data). Read about php://input
here.
2) Or you can serialize the data on the client and send it as text/plain
. The server can check the size the same way as described above. The server will need to unserialize the received content to be able to work with it. And if the client generates a hash of the serialized data and send it along in a header (X-Content-Hash
for example), the server can also generate a hash and check if it matches the one in the header. You won't need to check the hash, and can be a 100% sure the content is correct.
3) If you cannot change Content-Type
, you'll need something different from size to verify the content. The client could use an extra header (something like X-Form-Data-Fields
) to sum up the fields/keys/names of the content you're sending. The server could then check if all fields mentioned in the header are present in the content.
4) Another solution would be for the client to have a predefined key/value as last entry in the content. Something like:
--boundary
Content-Disposition: form-data; name="_final_field_"
TRUE
--boundary--
The server can check if that field is present in the content, if so the content must be complete.
update
When you need to pass binary data, you can't use option 1, but can still use option 2:
The client can base64
encode the binary entries, serialize the data (with any technique you like), generate a hash of the serialized data, send the hash as header and data as body.
The server can generate a hash of the received content, check the hash with the one in the header (and report a mismatch), unserialize the content, base64
decode the binary entries.
This is a bit more work then plainly using multipart/form-data
, but the server can verify with a 100% guarantee the content is the same as what the client sent.