Search code examples
phphtmlformshidden

is it better to append hidden field to form on submit rather than to have it before submit?


I am little concerned over keeping a hidden id field in my form as users can easily change the value by chrome dev tools or simply copy the codes , alter the value and submit the form.

For example I am updating student records and i have a hidden field like:

<input type="hidden" id="student_id" value="1" />

If I append the hidden field on form submit through jquery like this:

$('<input />').attr('type', 'hidden')
      .attr('name', "student_id")
      .attr('value', '1')
      .appendTo('#edit_record_form');

$('#edit_record_form').submit();

although I should double check on the server side. for the client side is this the best method I can go for better security?

would like to know what other methods would you pros suggest?

Thank you very much in advance.


Solution

  • although I should double check on the server side.

    100% Correct. Anything you do on the client side to validate is just a QoL feature for users. Since anyone could manufacture any request to your server endpoints, any filtering/validation done to this form presubmission is meaningless from a security perspective.

    (Also remember the user has access to your javascript and can refuse to run or modify its behavior on their page)

    Aside from this I think the pros and cons of this approach are:

    Pros:

    • The user is less able to screw things up.
    • Autosubmitting bots are less likely to mess up the form (This is either good or bad, if its a spam bot or your bot automatically testing features)
    • Features of how your interface works is less obvious (i.e. requires a higher level tech skill to glean knowledge about the interworkings of your app)

    Cons:

    • You have more code to write and maintain
    • There's one more opportunity for a bug to slip in right here
    • Users not running JS cannot successfully submit this form
    • Maybe a user runs a niche browser that executes the JS just slightly differently that results in this form being unusable
    • One day you want to change how the hidden forms work, now you have to change the server and the client validations

    In my opinion, the cons far aren't worth the pros. Just make your server secure and don't worry about curious users modifying their DOM. All they'll succeed in doing is get error messages and earn the privilege of redoing their work.