0

Is it possible to determine the size of POST data in bytes sent by a form, using JavaScript? The idea is to validate form size before submitted to avoid php errors concerning post_max_size

j08691
  • 204,283
  • 31
  • 260
  • 272
fcaserio
  • 726
  • 1
  • 9
  • 18
  • 1
    do you have a [mcve] of what you're trying to achieve ? – Ulysse BN Aug 28 '17 at 20:50
  • 4
    You shouldn't ever rely only on client-side checks and anything the client sends you. You should always be checking on the server-side. – j08691 Aug 28 '17 at 20:52
  • 1
    @j08691 is it possible to check the size of a post that exceeds post_max_size? I'm guessing op wants to let the user know if the upload size exceeds the server limit which doesn't seem possible to do server side. see https://stackoverflow.com/questions/2133652/how-to-gracefully-handle-files-that-exceed-phps-post-max-size – FuzzyTree Aug 28 '17 at 20:57

1 Answers1

1

As said by @j08691, it's better to check server-side to avoid a modification.

However, you can calculate all the bytes by get types of objects/variables of each data you want to send client => server and sum it.

It's long and not a good practice but you can do it.

const typeSizes = {
    'undefined': () => 0,
    'boolean': () => 4,
    'number': () => 8,
    'string': (item) => 2 * item.length,
    'object': (item) => Object.keys(item).reduce(
        (sum, key) => sum + sizeOf(key) + sizeOf(item[key]), 0
    ) };

const sizeOf = (value) => value === null ? 0 : typeSizes[typeof value](value);

This code give you a function named sizeOf which gives you the size of different types of data.

Knowing that you can compare the total with your "post_max_size" value and throw an error before the request.

Bye :)

Benjamin Audet
  • 463
  • 3
  • 12
  • tk you, of course server side validation is required, but client side validation adds an aditional level of validation and improves usability – fcaserio Aug 29 '17 at 14:02