tags:

views:

181

answers:

3

Not sure exactly how to describe this, but here goes ..

I have a large PHP function library that I want to expose via some sort of api interface.

For example, this query string:

api.php?function=myFunction&param1=xxx&param2=xxx&

Would translate into this:

$ret = myFunction( $param1, $param2 );

.. whereas this query string ..

api.php?function=myFunction&param2=xxx&param1=xxx&

Would translate into this:

$ret = myFunction( $param1, $param2 );

Note that I expect to have to rely on the query string to place the parameters required in the query, and in the order required.

Is this doable? I have a few ideas that may work, but thought I'd put it up here and perhaps get some better ideas from the PHP gurus.

Thanks -

A: 

collect your parameters into an array and pass it to to your function instead.

SilentGhost
+2  A: 

Use the call_user_func_array function to call a function with an array of its parameters.

And if you really want to extract the parameters from the query, you could use something like this:

$params = array();
foreach ($_GET as $name => $val) {
    if (preg_match('/^param[1-9]\d*$/', $name)) {
        $param[$name] = $val;
    }
}
ksort($params);
Gumbo
A: 

Just pass $_GET to your function. inside your function, you can look for the param you want. Or create a second function

function getFunctionCall($getParams)
{
    $function = $getParams['function'];
    returnArray['functionName'] = $function;

    $getArraySize = count($getParams);
    for(i = 1; $i < $getArraySize; $i++)
    {
        $param = $getParams['param'. $i];
        // do any cleaning you need on $param i ;
        $param = urldecode($param);
        returnArray['params']['param'.$i] = $param;
    }
    return $returnArray;

}

Now you have a return array and you can do something like this:

$mystuff = getFunctionCall($_GET);

$functionString = $mystuff['functionName'] . '("' . implode($mystuff[params], '","') . '")"; 

$myResult = eval($functionString);

However, be very careful doing this stuff... functionName could be any old thing under the sun including fopen's, fwrites, etc... It might be a good idea to create an "approved functions" list and check function name against that before allowing it to be called. Also, the way I put the parms in there as strings in the eval is pretty dangerous. You could get string escaping in the passed params. Probably better to do a for loop and have it eval the variable names instead of the variable contents as strings.

Finally, if you actually know the number of arguments to your function, it ouwld be much safer to just use

$results = $mystuff['functionName']($mystuff[params][param1]);

and so on.

Zak