Jump to content

Sanitising variables and mysql_real_escape_string


Jonob

Recommended Posts

Hi all,

 

I ensure that all variables input into my functions have been sanitised before using them. For example, if it meant to be an int, then I set it as such, if its a stirng, then I use mysql_real_escape_string, etc.

 

A conceptual question:

 

Assume that I have a public function inside a class. This function may in turn call one or more public or private functions inside the same class. Typically, at the start of each public function, I ensure that all parameters are properly sanitised just once in the public function, because I may call many private functions, all using the same $customer or $id variables. This saves me having to sanitise inside each private function. Something like this simplified example:

 

public function get_customers($id, $customer) {
  $id = (int)$id;
  $customer = mysql_real_escape_string($customer);
  $something = $this->get_single_customer($id);
  ...
}

private function get_single_customer ($id) {
  $sql = "SELECT id, name FROM customer WHERE id = $id";
  ...
}

 

My question:

is escaping/sanitising the variables only in the public function enough protection, or is it good practise to sanitise it on the actual sql string itself (i.e. inside each private function)?

Sanitise Escape where it matters - just before interpolating the variables into SQL string. Otherwise you run a risk of escaping variables twice or more.

 

Nothing stops you from checking if variables meet specific conditions at the beginning of each function though.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.