I've inherited a class in a project which is purposed to execute a function that exists in POST data from a specified class. I've tried to clean this up as much as possible as well as secure it against SQL injection but I'm wondering if I could have done a better job or written this better. Any assistance would be much appreciated!
class RegistrationProceduresController
{
public function __construct($username, $password, $host, $port, $dbname)
{
$SP = new RegistrationProceduresModel($username, $password, $host, $port, $dbname);
// Sanitize all the incoming POST data and move into an array of its own
$sanitized = array_map(array($this, 'sanitize'), $_POST);
// Check whether the method passed via our POST data is a public function within the model, or even exists
// at all. If not then skip to logging.
if(method_exists($SP, $sanitized['function']))
{
try
{
// Execute the function we passed via our post data against the model class post-sanitization.
$SP->$sanitized['function']();
}
catch(exception $ex)
{
json_encode("Exception when trying to execute a sanitized function in registration controller: " . $ex->getMessage());
}
}
else
{
try
{
$val = isset($sanitized['function']) ? $sanitized['function'] . " does not exist in model." : "was not specified";
json_encode("Function " . $val);
}
catch(exception $ex)
{
json_encode("Threw an error after failing to evaluate whether a $_POST method exists. Review registration controller. " . $ex->getMessage());
}
}
}
/// <summary>
/// Takes an input and returns it with all HTML characters stripped.
/// Protects against SQL injection.
/// </summary>
/// <param name="$input">Any string based input</param>
public function sanitize($input)
{
try
{
return htmlspecialchars(trim($input));
}
catch(exception $ex)
{
json_encode("Failed to sanitize POST data array in registration controller: " . $ex->getMessage());
}
return null;
}
}
This project is using POST data to call a function since it's being initialized by JavaScript. If there's a better way to call a PHP function from within JavaScript I would definitely, definitely value feedback on it!
$_POST
data to call a function! besides, your syntax is ambiguous: should PHP evaluate$SP->$sanitized['function']();
as$SP->{$sanitized}['function']();
where$sanitized
is a string, containing the name of a property, that has been assigned an array with afunction
key that has been assigned a lambda, or is it$SP->{$sanitized['function']()};
: a lambda returning a string, that is a property of$SP
or is it$SP->{$sanitized['function']}();
? use the latter to disambiguate \$\endgroup\$json_encode
a string: not a good idea.json_encode(array('error' => 'your custom string', 'msg' => $ex->getMessage(), 'code' => $ex->getCode()));
is what you want \$\endgroup\$