I am making a function so that I can post from Ajax using a general function where I just pass the params, to avoid having to create one php file for each Ajax function.
This is how my function looks right now in the PHP side after receiving, via post, the params that you can see in the code:
$class_name = $_POST['class_name'];
$function_name = $_POST['function_name'];
$params = "'" . implode("','", $_POST['params']) . "'";
$model = new $class_name();
//Apply the function
echo $model->$function_name($params);
It is working except from the part of the params… PHP is interpreting it as one param, what can I do so that $params is not intepreted as a single string?
The third line actually makes
$paramsa single string containing all the params.Depending on your framework (and how you’re passing the params in your Ajax stuff), you might be able to pass
$_POST['params']as is to the method, rather than passing$params. In which case you don’t need to build the string at all.If you need to call a function that expects the params to be passed individually, instead of in an array like that, try
If
$paramscontains 1, 2, and 3, and$function_nameis ‘foo’, the above expression would be equivalent to$model->foo(1, 2, 3).Note, this will let people call any public method of any class that’s available to your script. You need some kind of access control in order to keep people from running random stuff. As suggested in the comments on your question, a whitelist of some kind (even if it’s just a member variable that says whether the class was meant to be used by random code like this) would go a long way toward preventing security issues.