Handing $_POST or $_GET data using $wpdb - examples?

I’m trying to create a search interface for a custom few tables I added to the WP database.

I have no problem pulling data from the tables using $wpdb->get_results, but I’d like to see an example of how to properly handle $_POST or $_GET input (keeping security in mind also)

I’ve done some googling but haven’t yet come across a clear example, saw some people using “prepare” to help prevent sql injections. If someone can point me to a simple example on how to do this I would be very grateful!

Thank you.

The $_POST and $_GET arrays are what is known as tainted. This is a technical term meaning that what they contain can be anything - which might or might not be valid.

So the first step in processing them is to either validate or sanitize them. If the values were input by a user you should validate them. If it is a set value that should be valid but could be tampered with then the fields should be sanitized.

It is only once you have validated or sanitized the fields that you should then move them to a new field name (which will then be an untainted field). The reason for moving the value after validation or sanitizing is that you then know that the value in the field is valid simply by looking at the field’s name as you can’t tell by looking at the original array names whether you are seeing them before or after they have been confirmed to be valid.

So the calls to do the validation will all look someting like this:

$x = validateX($_POST['x']);

the validateX function will contain the code that takes the $_POST['x'] value and validates or sanitizes it. Just what that will require will depend on what x is.

Using prepare/bind for all your database calls has nothing to do with validating inputs - it has to do with keeping the data and code for the database calls separate so that the data cannot be mistaken for code. If you jumble the data and code together then anything in the data that looks like code could be mistaken for code and make a mess of the call (or even run instead of being saved). That doing this also eliminates the possibility of injecting code as the data is kept completely separate. This bonus feature is called defense in depth as it means that if someone gets past the validation due to a bug in the validation code they still can’t inject code into the database call.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.