What’s the best practice for making sure that certain ajax calls to certain pages are only accepted from authenticated users?
Let’s say that I have a main page called blog.php (I know, creativity abounds). Let’s also say that there is a page called delete.php which looks for the parameter post_id and then deletes some entry from a database.
In this very contrived example, there’s some mechanism on blog.php which sends a request via ajax to delete.php to delete an entry.
Now this mechanism is only going to be available to authenticated users on blog.php. But what’s to stop someone from just calling delete.php with a bunch of random numbers and deleting everything in site?
I did a quick test where I set a session variable in blog.php and then did an ajax call to delete.php to return if the session variable was set or not (it wasn’t).
What’s the accepted way to handle this sort of thing?
OK. I must have been crazy the first time I tried this.
I just did another test like the one I described above and it worked perfectly.
You were correct in trying to use session variables. Once your user authenticates, you should store that information in their session so that each subsequent page view will see that. Make sure you are calling
session_start() on both pages (blog.php and delete.php) before accessing $_SESSION. Also make sure you have cookies enabled — and if not, you should pass an additional parameter in the query string, usually PHPSESSID=<
It is not recommended that you rely on sessions for authentication without taking additional actions.
Read more on.