How to get complete current url for Cakephp

前端 未结 24 1220
长情又很酷
长情又很酷 2020-12-08 00:10

How do you echo out current URL in Cake\'s view?

相关标签:
24条回答
  • 2020-12-08 00:33

    for CakePHP 3.x You can use UrlHelper:

    $this->Url->build(null, true) // output http://somedomain.com/app-name/controller/action/params
    
    $this->Url->build() // output /controller/action/params
    

    Or you can use PaginatorHelper (in case you want to use it in javascript or ...):

    $this->Paginator->generateUrl() // returns a full pagination URL without hostname
    
    $this->Paginator->generateUrl([],null,true) // returns a full pagination URL with hostname
    
    0 讨论(0)
  • 2020-12-08 00:33

    I use $this->here for the path, to get the whole URL you'll have to do as Juhana said and use the $_SERVER variables. There's no need to use a Cake function for this.

    0 讨论(0)
  • 2020-12-08 00:37

    for CakePHP 3:

    $this->Url->build(null, true) // full URL with hostname
    
    $this->Url->build(null) // /controller/action/params
    
    0 讨论(0)
  • 2020-12-08 00:39

    for cakephp3+:

    $url = $this->request->scheme().'://'.$this->request->domain().$this->request->here(false);
    

    will get eg: http://bgq.dev/home/index?t44=333

    0 讨论(0)
  • 2020-12-08 00:40

    I prefer this, because if I don't mention "request" word, my IDE gives warning.

    <?php echo $this->request->here; ?>
    

    API Document: class-CakeRequest


    Edit: To clarify all options

    Current URL: http://example.com/en/controller/action/?query=12
    
    // Router::url(null, true)
    http://example.com/en/controller/action/
    
    // Router::url(null, false)
    /en/controller/action/
    
    // $this->request->here
    /en/controller/action/
    
    // $this->request->here()
    /en/controller/action/?query=12
    
    // $this->request->here(false)
    /en/controller/action/?query=12
    
    // $this->request->url
    en/controller/action
    
    // $_SERVER["REQUEST_URI"]
    /en/controller/action/?query=12
    
    // strtok($_SERVER["REQUEST_URI"],'?');
    /en/controller/action/
    
    0 讨论(0)
  • 2020-12-08 00:40

    Getting current URL for CakePHP 3.x ?

    In your layout :

    <?php 
        $here = $this->request->here();
        $canonical = $this->Url->build($here, true);
    ?>
    

    You will get the full URL of the current page including query string parameters.

    e.g. http://website.example/controller/action?param=value

    You can use it in a meta tag canonical if you need to do some SEO.

    <link rel="canonical" href="<?= $canonical; ?>">
    
    0 讨论(0)
提交回复
热议问题