There is a way to inject code via ajax or to fake information?
Like to send Ajax from my website to another website that use ajax?
If so how can I prevent this that I can send ajax only from my website?
There is a way to inject code via ajax or to fake information?
Like to send Ajax from my website to another website that use ajax?
If so how can I prevent this that I can send ajax only from my website?
You're probably looking for CSRF (cross-site request forgery) protection. The issue is that your site has no idea where AJAX requests are coming from. The generally accepted solution is to create a token that is sent from your site which is required to be sent along with AJAX requests.
This token would be unique to a user session and output somewhere in the HTML of your page. This makes it challenging for other sites to capture this token.
To give you the basic idea, you would do something like this:
$_SESSION['csrf_token'] = md5(uniqid(rand(), TRUE));
Then you could for example output this as a JavaScript variable
<script>
window.CSRF_TOKEN = '<?php echo $_SESSION['csrf_token']; ?>';
</script>
If you happen to be using jQuery, you can use ajaxSend()
to add the token to each request
$.ajaxSend(e, jqXHR, settings) {
if (!settings.data) settings.data = {};
settings.data['csrf_token'] = window.CSRF_TOKEN;
}
Finally, on the backend you would check that $_REQUEST['csrf_token'] ==
$_SESSION['csrf_token']` to validate the request. It's generally a good idea for these tokens to be one-time use if possible. Storing the time the token was generated and making sure it's used within a reasonable time frame is also a good idea.