Get current URL/URI without some of $_GET variables

后端 未结 15 1918
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 09:10

How, in Yii, to get the current page\'s URL. For example:

http://www.yoursite.com/your_yii_application/?lg=pl&id=15

but excluding the

相关标签:
15条回答
  • 2021-01-30 09:18

    I don't know about doing it in Yii, but you could just do this, and it should work anywhere (largely lifted from my answer here):

    // Get HTTP/HTTPS (the possible values for this vary from server to server)
    $myUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && !in_array(strtolower($_SERVER['HTTPS']),array('off','no'))) ? 'https' : 'http';
    // Get domain portion
    $myUrl .= '://'.$_SERVER['HTTP_HOST'];
    // Get path to script
    $myUrl .= $_SERVER['REQUEST_URI'];
    // Add path info, if any
    if (!empty($_SERVER['PATH_INFO'])) $myUrl .= $_SERVER['PATH_INFO'];
    
    $get = $_GET; // Create a copy of $_GET
    unset($get['lg']); // Unset whatever you don't want
    if (count($get)) { // Only add a query string if there's anything left
      $myUrl .= '?'.http_build_query($get);
    }
    
    echo $myUrl;
    

    Alternatively, you could pass the result of one of the Yii methods into parse_url(), and manipulate the result to re-build what you want.

    0 讨论(0)
  • 2021-01-30 09:22

    In Yii2 you can do:

    use yii\helpers\Url;
    $withoutLg = Url::current(['lg'=>null], true);
    

    More info: https://www.yiiframework.com/doc/api/2.0/yii-helpers-baseurl#current%28%29-detail

    0 讨论(0)
  • 2021-01-30 09:23

    For Yii2: This should be safer Yii::$app->request->absoluteUrl rather than Yii::$app->request->url

    0 讨论(0)
  • 2021-01-30 09:23
    echo Yii::$app->request->url;
    
    0 讨论(0)
  • 2021-01-30 09:25

    Something like this should work, if run in the controller:

    $controller = $this;
    $path = '/path/to/app/' 
      . $controller->module->getId() // only necessary if you're using modules
      . '/' . $controller->getId() 
      . '/' . $controller->getAction()->getId()
    . '/';
    

    This assumes that you are using 'friendly' URLs in your app config.

    0 讨论(0)
  • 2021-01-30 09:26

    Yii 1

    Yii::app()->request->url
    

    For Yii2:

    Yii::$app->request->url
    
    0 讨论(0)
提交回复
热议问题