Having trouble with array_map when handling $_POST data

520 views Asked by At

I'm working on updating some code that calls a function based on post data. The original class looks like this:

class RegistrationProceduresController
{
    public function __construct($username, $password, $host, $port, $dbname)
    {
        $SP = new RegistrationProceduresModel($username, $password, $host, $port, $dbname);

        if(method_exists($SP, $SP->$_POST['function']()))
        {
            $SP->$_POST['function']();
        }
        else
        {
            die("Function does not exist" . isnull($SP->$_POST['function'](), ". No function was specified"));
        }
    }
}

I'm trying to update this class to sanitize the data before executing a function based on post data. So far I've come to the following:

class RegistrationProceduresController
{
    public function __construct($username, $password, $host, $port, $dbname)
    {
        $SP = new RegistrationProceduresModel($username, $password, $host, $port, $dbname);

        // Sanitize all the incoming data
        $sanitized = array_map('sanitize', $_POST);

        if(method_exists($SP, $SP->$sanitized['function']()))
        {
            $SP->$sanitized['function']();
        }
        else
        {
            die("Function does not exist" . isnull($SP->$sanitized['function'](), ". No function was specified"));
        }
    }

    public function sanitize($input)
    {
        return htmlspecialchars(trim($input));
    }
}

This brings me to the following:

Warning: array_map() expects parameter 1 to be a valid callback, function 'sanitize' not found or invalid function name in C:\DWASFiles\Sites\junglegym\VirtualDirectory0\site\wwwroot\wp-content\plugins\qcore\qcore_waitress.php on line 17Fatal error: Method name must be a string in C:\DWASFiles\Sites\junglegym\VirtualDirectory0\site\wwwroot\wp-content\plugins\qcore\qcore_waitress.php on line 19

Which is this line:

if(method_exists($SP, $SP->$sanitized['function']()))

I perhaps incorrectly thought this would be how I could use my new variable ($santized) but it looks like I'm totally wrong. What would be the most efficient way to tackle this problem?

1

There are 1 answers

2
Dickie On BEST ANSWER

You're using an object method, not a native function, as the array_map callback parameter. Try calling array_map like this:

$sanitized = array_map(array($this, 'sanitize'), $_POST);

See Callbacks for more info.

method_exists just needs a string of the method name as its second parameter, try calling it like:

method_exists($SP, $sanitized['function']);