patternphpMinor
Generating the property name of an object
Viewed 0 times
thegeneratingpropertynameobject
Problem
$roleId = pg_escape_string($_POST['role']);
$grantValue = pg_escape_string($_POST['grant']);
$feature = pg_escape_string($_POST['feature']);
$permission = pg_escape_string($_POST['permission']);
$permissionsModel = new Permissions();
$record = $permissionsModel->getPermission($roleId);
//assemble object's property name based on the action taking place and save changes.
$property = trim($feature . '_' . $permission);
$record->$property = $grantValue;
$record->save(false);Here is an example of an actual property of the object:
$record->report_w;$record->facebook_d;My second question is about escaping the data: can you suggest a better way of validating user input?
Solution
Yes, this is bad practice, sometimes
You are giving the user the option to dynamically change object properties. What if the property doesn't exist? What if a boogie monster passes by?
Sometimes, generating the property could be usefull, but only do this when you trust the thing that is generating the property. Is it a user? bad practice. Is it the program itself, wel, maybe.
escaping data
Don't escape data, don't try and remove all 'bad' data. A better approach is to check for a whitelist.
$role has to be an integer, so make sure it is
feature and permission probably only accept alpha characters? And probably only lower case? So let's check that:
whitelists are better
Use whitelists instead of blacklist. It's easier to know what is allowed then to know what isn't. Simply because we can't know all the bad things out there
You are giving the user the option to dynamically change object properties. What if the property doesn't exist? What if a boogie monster passes by?
Sometimes, generating the property could be usefull, but only do this when you trust the thing that is generating the property. Is it a user? bad practice. Is it the program itself, wel, maybe.
escaping data
Don't escape data, don't try and remove all 'bad' data. A better approach is to check for a whitelist.
$role has to be an integer, so make sure it is
<?php
if ( preg_match('/^[0-9]+$/',$_POST['role']) != 1 )
{
throw new Exception('I need an int');
}feature and permission probably only accept alpha characters? And probably only lower case? So let's check that:
if ( preg_match('/^[0-9a-z]+$/',$_POST['role']) != 1 )
{
throw new Exception('I need an int');
}whitelists are better
Use whitelists instead of blacklist. It's easier to know what is allowed then to know what isn't. Simply because we can't know all the bad things out there
Code Snippets
<?php
if ( preg_match('/^[0-9]+$/',$_POST['role']) != 1 )
{
throw new Exception('I need an int');
}if ( preg_match('/^[0-9a-z]+$/',$_POST['role']) != 1 )
{
throw new Exception('I need an int');
}Context
StackExchange Code Review Q#55967, answer score: 3
Revisions (0)
No revisions yet.