Sunday, 15 August 2010

regex - Proper order of PHP input validation -



regex - Proper order of PHP input validation -

obviously should validate user input info on server side. i'm curious considered "proper" input validation , order of should done.

as of right (and recent projects past) have done way:

get user input, instantiate object, , phone call method:

if(isset($_post['addcat'])) { $db = new dbconnection; $categories = new category($db); if($categories->insert_cat($_post['name']) === true) { echo "category inserted successfully!"; } }

the method called instantiated object which:1. escapes user input2. istantiates data_validation object (see validation object below)

class categories { public function insert_cat($catname) { $catname = $this->mysqli->real_escape_string($catname); $validate = new data_validation; if(!($validate->validate_string($catname))) { echo "invalid characters found in category name"; die(); } $query = $this->mysqli->query("insert categories(name) values ('".$catname."')"); if($query === false) { printf("error: %s\n", $this->mysqli->error); die(); } else { homecoming true; } } }

data_validation class which:1. trims data2. matches info regular expression3. returns info insert_cat method database insertion

class data_validation { public function validate_string($data) { // remove excess whitespace $data = trim($data); if ( preg_match("/^[0-9a-za-z \.\-\'\"]+$/", $data) ) { homecoming true; } else { //return 'not valid string'; homecoming false; } } }

so in short question is: proper first escape data, trim it, compare regular expression, add together htmlentites() or of sorts preserve formatting or should done in different order?

any tips improve security habits more welcome!

on the open web application security project you'll find if not info need validation , security in general.

php regex validation

No comments:

Post a Comment