You cannot guarantee that the data came from the form. A POST request is just a POST request, it can be generated in any number of ways. The HTML form is just one of those ways that are very user friendly. Your server needs to check whether the data received using the POST request is really valid or not, whether to act on it or not.
Having said that, there are things that can help you limit and confirm the data that is sent. First of all, it is necessary for the user to register when using cookies. This eliminates random requests from anonymous users. Secondly, you can embed a token in a hidden field in a form that you also save in a user session. A POST request must contain this token in order to be valid. A token is just a pseudo-random string.
You can improve this by preparing a hash of the form fields that you expect from the user. If the form value should be read-only, you can include this value in the hash. For instance:.
$rand = md5(mt_rand()); $hash = sha1('lastname:firstname:email:' . $rand); $_SESSION['rand'] = $rand; $_SESSION['hash'] = $hash; // on form submit: $keys = array_keys($_POST); $checkHash = sha1(join(':', $keys) . ':' . $_SESSION['rand']); if ($checkHash != $_SESSION['hash']) { die('Form submission failed token validation'); }
This is just a quick example, you probably want to sort the keys alphabetically to make sure you get the same hash, etc. It demonstrates the concept of a user who needs to have a unique token for each request, although this prevents hardening with forms and providing more or less data than is required.
This still does not mean that the user actually used your form to submit data.
source share