Professional CodeIgniter

(singke) #1

Chapter 9: Security and Performance


273


Now that you ’ ve written the db_clean() function, which incorporates the substr() function, you
want to change these three functions to look like the following code. Notice that it is important that you
run dohash() on the password and then pass it to db_clean. Doing it in this order will ensure that you
get the right 16 characters stored in the table.

If you want to avoid trouble, simply change your password field length to 32 characters and then use 32
as your size limiter on the db_clean() function.

function addUser(){
$data = array(‘username’ = > db_clean($_POST[‘username’],16),
‘email’ = > db_clean($_POST[‘email’],255),
‘status’ = > db_clean($_POST[‘status’],8),
‘password’ = > db_clean(dohash($_POST[‘password’]),16)
);
$this- > db- > insert(‘admins’,$data);
}

function updateUser(){
$data = array(‘username’ = > db_clean($_POST[‘username’],16),
‘email’ = > db_clean($_POST[‘email’],255),
‘status’ = > db_clean($_POST[‘status’],8),
‘password’ = > db_clean(dohash($_POST[‘password’]),16)
);
$this- > db- > where(‘id’,id_clean($_POST[‘id’]));
$this- > db- > update(‘admins’,$data);
}

function verifyUser($u,$pw){
$this- > db- > select(‘id,username’);
$this- > db- > where(‘username’, db_clean($u,16) );
$this- > db- > where(‘password’, db_clean(dohash($pw),16) );
$this- > db- > where(‘status’, ‘active’);
$this- > db- > limit(1);
$Q = $this- > db- > get(‘admins’);
if ($Q- > num_rows() > 0){
$row = $Q- > row_array();
$_SESSION[‘userid’] = $row[‘id’];
$_SESSION[‘username’] = $row[‘username’];
}else{
$this- > session- > set_flashdata(‘error’, ‘Sorry, your username or password is
incorrect!’);
}
}

Securing the MCats Model


Once you ’ ve got the helper functions id_clean() and db_clean() in place, thanks to your work in
the “ Securing the MAdmins Model ” section, you can make short work of the rest of the models.
The MCats model, for example, only needs id_clean() in getCategory() , getSubCategories() ,
addCategory() , updateCategory() , and deleteCategory(). The addCategory() and
updateCategory() functions also need the db_clean() function in any place you ’ re adding
information to the database.
Free download pdf