I’m stuck in this situation where I need to validate if it’s the right user sending the request/information to the server. For example, a user submits a delete friend request, in the URL as parameters I include the friend’s id (another member id); should I also include the member asking for the friend delete request’s id?
I’m just trying to validate or make sure it’s the right user sending the request. What’s the best way to go about this in general? If the user is logged in can we just validate by logged in member’s id? Or is there a better way?
Without knowing how your authentication works, it’s a little difficult to say.
When I’ve had to do this in the past, I’ve used a combination of server-side authentication to identify the user sending the request, and URL parameters to specify what they want to delete. A user needs to be logged in to send a Delete request, and I’m tracking their userID with a $_SESSION variable. So when I get a Delete request, the SQL looks vaguely like:
As halfer explains in the comments, this is a generally bad way of doing things, as it opens an SQL injection vulnerability in the code. You can consider a couple of ways of avoiding that.
Firstly, you can sanitize the data – if you know that your friendID is always going to be an integer, you can check for that. A regular expression to check for non-numeric characters will work – if there’s anything dodgy in there, you can deal with it appropriately and not pass it to the database.
The second approach is the one I prefer – when you make your query, you can use a prepared statement, and bind the parameters to it. Using PDO, you’ll end up with something that looks like: