Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make HTML form data unchangeable, but still able to post

I have an HTML form that calculates total quantity and price. I can put this total into an input field to be submitted. However, I don't want the user to be able to change it. If i put it in a div and display it, it's not submitted with the form.

How do I display the total and submit it without letting the user change it?

I'm probably missing something basic here. Any help appreciated.

like image 267
wibberding Avatar asked Jan 27 '26 17:01

wibberding


2 Answers

If you want no security (via tamper prevention) use the readonly attribute:

HTML5

<input type="text" value="MY_DATE" readonly>

HTML4

<input type="text" value="MY_DATE" readonly="readonly" />

The type="text" can be omitted, but I personally find it helps newer developers see what type the input is at first glance.

Your best bet (for proper security) is to either encrypt or sign the data and send it as a hidden form element. Then once it comes back to the server you can either decrypt it (to keep using it) or check the signature to ensure it hasn't been tampered with.

Then from a frontend point of view you can just make the data not an input (or readonly) and then you should be golden. The technique is used a lot by web frameworks such as CakePHP when it supplies the id in a hidden element, and signs it to ensure no tampering.

Server

signed = sha(date, salt);

Frontend

input[type="hidden"].value = signed;
input[type="text"][readonly].value = date;

Server (on submit)

if(signed === sha(POST[date], salt) {
    //date has not changed
} else {
    // date has changed
}

For a11y (accessibility) you should still use a form element when showing data related to what is being sent off, so using a text input is advised over a div. Using readonly is far better off than disabled as disabled will remove the input from the request all together, resulting in your server not receiving it. See here.

Here is a quick snippet of how to do it in PHP.

Server

$salt = '...'; //This should be stored securely in your application.
$date = ... //However you are storing your date.
$signed_date = hash('sha512', $salt . $date);

Frontend

<input type="hidden" value="<?php echo $signed_date; ?>" name="signed_date" />
<input type="text" value="<?php echo $date; ?>" readonly name="date" />

Server (on submit)

$salt = '...';
$date = &$_POST['date'];
$signed_date = &$_POST['signed_date'];

if(hash('sha512', $salt . $date) === $signed_date) {
    echo "wooo!";
} else {
    echo "ohhh";
}
like image 108
jshthornton Avatar answered Jan 30 '26 07:01

jshthornton


Give the input a readonly attribute:

<input readonly value='cannot be changed' />

like image 22
vsync Avatar answered Jan 30 '26 05:01

vsync



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!