Waterwaker
Waterwaker

Reputation: 3

Blocking remote access through PHP

Getting this out of the way; I don't frequently do much in php or database programming, so I'm just trying to be extra careful in this current project.

So basically, I have a site powered by a database and I have some Jquery code that uses the "post" method to insert rows into the database. As soon as I started I had my thoughts about security, seeing as people can't see my php, but can see my Javascript. As soon as I finished setting up the system I did a test and running the jquery does insert information even if I'm on a remote source... which can obviously lead to a possible major security problem. So being as unrefined as I am, I just want to know how I should prevent this and secure the system better?

And... Please don't insult me or be rude... I understand that I may be stupid or whatever, but I'm just trying to learn!

Upvotes: 0

Views: 639

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174662

This is what Cross Site Request Forgery (CSRF) and the same origin policy sandbox are designed to prevent.

From another point of view, how do you stop someone from writing a form on their site and submitting it as a POST request to your script to add junk records?

Typically CSRF protection is provided by your framework. If you want to implement it directly in PHP, it is quite simple.

  1. Generate a unique token that from your server's code, and add it to the session.
  2. Embed it as a hidden field in the form.
  3. On the script that accepts the form, check for the presence of this hidden field.

If the field exists, match it against what is in the session, if they match - then it is a legitimate request.

If they don't match (or the field is missing), then its a remote request and you can reject it.

This page provides some PHP code to implement the above.

Once you have done that, you need to make sure that the jquery script can be authenticated the same way. This snippet details steps to implement the same technique in jquery.

Upvotes: 4

Related Questions