views:

595

answers:

1

Hi Guys,

could you help me with following questions. How do i get the:

absolute/relative current url

absolute/relative application url

I could of course use native php to get it but i think i should rather use ko3 functions.

Any idea how that works?

Thanks in advance!

+4  A: 

Tried to make a controller that outputted them all correctly. Let me know if any of them are off.

class Controller_Info extends Controller
{
    public function action_index()
    {
        $uris = array
        (
            'page' => array
            (
                'a' => Request::instance()->uri(),
                'b' => URL::base(TRUE, FALSE).Request::instance()->uri(),
                'c' => URL::site(Request::instance()->uri()),
                'd' => URL::site(Request::instance()->uri(), TRUE),
            ),

            'application' => array
            (
                'a' => URL::base(),
                'b' => URL::base(TRUE, TRUE),
                'c' => URL::site(),
                'd' => URL::site(NULL, TRUE),
            ),
        );

        $this->request->headers['Content-Type'] = 'text/plain';
        $this->request->response = print_r($uris, true);
    }

    public function action_version()
    {
        $this->request->response = 'Kohana version: '.Kohana::VERSION;
    }

    public function action_php()
    {
        phpinfo();
    }

}

Outputs this:

Array  
(
    [page] => Array
        (
            [a] => info/index
            [b] => /kohana/info/index
            [c] => /kohana/info/index
            [d] => http://localhost/kohana/info/index
        )
    [application] => Array
        (
            [a] => /kohana/
            [b] => http://localhost/kohana/
            [c] => /kohana/
            [d] => http://localhost/kohana/
        )
)

Technically speaking, it's actually only the first page url that is a real relative url, since all the others either start with / or http://.


Needed to get the url for the current page myself, so decided to extend the url class. Thought I could share it here. Let me know what you think :)

/**
 * Extension of the Kohana URL helper class.
 */
class URL extends Kohana_URL 
{
    /**
     * Fetches the URL to the current request uri.
     *
     * @param   bool  make absolute url
     * @param   bool  add protocol and domain (ignored if relative url)
     * @return  string
     */
    public static function current($absolute = FALSE, $protocol = FALSE)
    {
        $url = Request::instance()->uri();

        if($absolute === TRUE)
            $url = self::site($url, $protocol);

        return $url;
    }
}

echo URL::current();            //  controller/action
echo URL::current(TRUE);        //  /base_url/controller/action
echo URL::current(TRUE, TRUE);  //  http://domain/base_url/controller/action
Svish

related questions