I am trying to make a like/unlike system, when a user clicks like on a post, his/her user id (which is stored in a session) and the post id will be stored in a database through an ajax call.
Then I thought what if some user make a html form with invisible input field (which has one of his post ids) on another domain and give its link to a user who checked remember me later or is viewing my site.
The user will click the button and The form will POST post id to my site, session contains user id and these will be stored in database.
No good solution comes to my mind. Is there any way more reliable than HTTP referrer to prevent this?
Thanks in advance
One way is to insert a secret variable into the HTML which is specific to a user's session. This can prevent cross site forgery.
In PHP you'd generate a random 'key' and store it in the session:
$_SESSION['myFormVar'] = md5(mt_rand());
Then in a form, you'd add as a hidden variable:
<input type="hidden" name="chkVar" value="<?=$_SESSION['myFormVar']?>"/>
You should submit your form via POST and preferably over HTTPS, making it harder (but not impossible) to intercept the value of chkVar.
In the code that processes your posted form, compare the posted chkVar against your session variable. In an ideal world, you'd have a unique chkVar per request, however using one which is the same for an entire session often works fine and guards against most csrf attacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With