Help with PHP method_exists ()

I am writing a catch all method for my controller for ajax. It's called "ajax": P

This is what currently looks like

public function ajax($method = null) {

    if ( ! $method OR ! request::is_ajax()) {

        return false;

    }


    if (method_exists(array($this, 'searchModel'), $method)) {
        echo $this->searchModel->$method();

    }

    exit;



}

      

If it's not obvious, I want ajax to help out first if it thinks it's not an Ajax request, then check mine $this->searchModel

to see if it has a method that was passed as an ajax method.

If it finds a method, it should iterate over its return value and then exit.

My problem: I can't seem method_exists()

to find the method! I know it exists ... I've even heavily coded (for testing purposes) the methods that I know exist.

This made me a little crazy, can anyone tell me what I am doing wrong?

Thank!

PS I'm using Kohana framework but I don't think it matters.

UPDATE

Do you think that exposing your internal names to JavaScript methods (i.e. public) can be a security issue?

+2


source to share


2 answers


You use the first argument method_exists()

as if it supported a callback argument, but it doesn't accept a callback. It only accepts an object instance or class name (string) for testing static methods.

Try the following:

if (method_exists($this->searchModel, $method)) {
    echo $this->searchModel->$method();
}

      




Repeat your second question, yes, I think this is a security issue. You have not confirmed the correctness of the request. I would not use the "catch-all" solution you developed.

+4


source


I think your code should say:

if(method_exists($this->searchModel, $method))
    echo $this->searchModel->$method();

      



However, it's a bad idea to expose all the methods of your searchModel object to the world, so you must prefix ajax methods with " ajax_

" or something similar so that you can only call methods with that prefix:

// given that $method is 'user_login' ...
$realMethod = 'ajax_' . $method;    
if(method_exists($this->searchModel, $realMethod))
    // calls $this->searchModel->ajax_user_login();
    echo $this->searchModel->$realMethod();

      

+2


source







All Articles