Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure ajax form POST

I was wondering how to develop a secure form post through AJAX.

For example, i have:

My HTML form.

My JavaScript handling the submit.

The submit url is "post_data.php"

The posted data is:

id=8&name=Denis

The PHP verifies if variables id and name are POSTED and their data type. If this is ok it proceed to do some stuff on a database.

My question is, how can i prevent someone from creating his own html form, outside my web site, or whatever, and posting false data to my PHP script?

Imagine that data realy exists on my database, this could be bad.

Thanks

like image 453
dciccale Avatar asked May 17 '26 04:05

dciccale


2 Answers

One very common way to do this is to have a token of some kind included in a <hidden> field on your form, and the same one saved in a session variable (or somewhere else) on your server. When the post is submitted, you check that the token is valid.

Someone else could still forge a token, but they can't (in any easy way, at least) force you to save the same token on your server, so no other form than your own will be accepted.

This is, for example, how the built-in support for this in ASP.NET MVC works.

like image 96
Tomas Aschan Avatar answered May 19 '26 04:05

Tomas Aschan


The token method is probably the most effective way. With that said, you should never assume that the data is coming from your own form even once you have these other security measures in place. Validating data will always be important.

like image 38
cjroth Avatar answered May 19 '26 04:05

cjroth



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!