I have a form that users use to add their email address and name to sign up for a newsletter.
On submit an ajax request transmits the data to my database.
Should I use any sort of protection to stop someone else adding entries to the database, eg. if another site linked their form to my ajax request url, then they would be adding data to my database.
How can I stop this?
There are some methods to secure AJAX calls and I give you a simple solution. This one use php session where a random key is generated and saved in session, then used in AJAX request to validate call request. The new url endpoint is http://www.myapp.ext/ajax/myplugin?skey=<Random key> .
An AJAX call can be secured the same way any HTTP request can be secured. First of all, use POST as opposed to GET to hide any sensitive parameters from the URL. Secondly, cross check all your requests for CSRF(Cross-Site Request Forgery) by using a CSRF token.
Yes it's safe. As far as load, that's up to your hardware and how you write it, but it has no worse effect than users refreshing the page (arguably less considering the overhead of an AJAX call over a standard page load). You can adjust the timeout in the web.
If you're really serious about it:
$_SESSION
)Even better, just create a random string, and only send its hash - if you match the hash you get from the form with the one generated from the original string, you have a valid request.
This will kill you caching though, so I cannot really recommend it as a "just do this" solution, depends on your volume.
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