47

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 $GET_['lg'] (without parsing the string manually)?

I mean, I'm looking for something similar to the Yii::app()->requestUrl / Chtml::link() methods, for returning URLs minus some of the $_GET variables.

Edit: Current solution:

unset $_GET['lg'];

echo Yii::app()->createUrl(
  Yii::app()->controller->getId().'/'.Yii::app()->controller->getAction()->getId() , 
  $_GET 
);
trejder
  • 17,148
  • 27
  • 124
  • 216
Sebastian
  • 709
  • 1
  • 8
  • 15
  • possible duplicate of [How to remove the querystring and get only the url?](http://stackoverflow.com/questions/6969645/how-to-remove-the-querystring-and-get-only-the-url) – T.Todua Apr 16 '15 at 13:08
  • http://stackoverflow.com/questions/8413062/get-current-url-uri-without-some-of-get-variables – Sarkhan Aug 17 '15 at 11:55

17 Answers17

80

Yii 1

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

For Yii2:

Yii::$app->request->url
Community
  • 1
  • 1
Felipe
  • 11,557
  • 7
  • 56
  • 103
  • This should be the correct answer, since the asker want to be done with Yii – GusDeCooL Nov 25 '12 at 11:24
  • 3
    This is not what the poster asked for. See the answer below: http://stackoverflow.com/questions/8413062/yii-how-do-you-get-current-url-uri-without-some-of-get-variables/22460712#22460712 – marcovtwout Mar 17 '14 at 17:06
  • 3
    This is the wrong answer. User needs to EXCLUDE some GET parameters. – Michael Butler Sep 17 '14 at 19:47
  • This anwer has a lot of up votes but it is misleading, @MichaelButler answer is very good but you can see shorter yii2 specific answer http://stackoverflow.com/questions/8413062/get-current-url-uri-without-some-of-get-variables/33409343#33409343 – Vladimir Nov 19 '15 at 08:24
  • 4
    Yii2: Yii::$app->request->url – Sukma Saputra Aug 31 '16 at 08:42
32
Yii::app()->createAbsoluteUrl(Yii::app()->request->url)

This will output something in the following format:

http://www.yoursite.com/your_yii_application/
Bhargav
  • 871
  • 1
  • 13
  • 24
  • This should be the correct answer, sometimes the url includes not just controller and action, but view, and depends on the route methods. – Mahomedalid Oct 20 '14 at 16:26
  • 1
    I think this is wrong. Because `createAbsoluteUrl` expects a route not a URL. The author's original solution is quite right but a more correct one would be: `$this->createUrl($this->getRoute(), $_GET)` and before calling it, unset from `$_GET` the params that you don't wish. – Alexandru Trandafir Catalin Sep 29 '16 at 18:41
  • **This is terrible answer, don't use it!** It will give you a bunch of bugs when your URLs does not match routes. For example if `/news/index` should display route `news/view` for `News` model with slug `index`. With this answer you will get incorrect URL - it will redirect you to URL for `/news/index` *route* instead `/news/view`. – rob006 Jun 09 '18 at 13:07
23

Yii 1

Most of the other answers are wrong. The poster is asking for the url WITHOUT (some) $_GET-parameters.

Here is a complete breakdown (creating url for the currently active controller, modules or not):

// without $_GET-parameters
Yii::app()->controller->createUrl(Yii::app()->controller->action->id);

// with $_GET-parameters, HAVING ONLY supplied keys
Yii::app()->controller->createUrl(Yii::app()->controller->action->id,
    array_intersect_key($_GET, array_flip(['id']))); // include 'id'

// with all $_GET-parameters, EXCEPT supplied keys
Yii::app()->controller->createUrl(Yii::app()->controller->action->id,
    array_diff_key($_GET, array_flip(['lg']))); // exclude 'lg'

// with ALL $_GET-parameters (as mensioned in other answers)
Yii::app()->controller->createUrl(Yii::app()->controller->action->id, $_GET);
Yii::app()->request->url;

When you don't have the same active controller, you have to specify the full path like this:

Yii::app()->createUrl('/controller/action');
Yii::app()->createUrl('/module/controller/action');

Check out the Yii guide for building url's in general: http://www.yiiframework.com/doc/guide/1.1/en/topics.url#creating-urls

marcovtwout
  • 5,230
  • 4
  • 36
  • 45
  • Yes, great answer! (and indeed the only correct one to the question) Could use an update it for Yii2 too though.. – Flion Mar 10 '15 at 13:53
  • 4
    found it: __Yii2__: ```Yii::$app->urlManager->createUrl(array_merge([Yii::$app->requestedRoute], $getParams));``` – Flion Mar 10 '15 at 14:05
15

To get the absolute current request url (exactly as seen in the address bar, with GET params and http://) I found that the following works well:

Yii::app()->request->hostInfo . Yii::app()->request->url
James Fletcher
  • 920
  • 11
  • 13
12

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

rob006
  • 21,383
  • 5
  • 53
  • 74
Vladimir
  • 445
  • 8
  • 13
6

You are definitely searching for this

Yii::app()->request->pathInfo
Dinesh Patil
  • 1,042
  • 10
  • 13
6

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.

Community
  • 1
  • 1
DaveRandom
  • 87,921
  • 11
  • 154
  • 174
  • This is really helpful. My only consideration is that Yii is using either the 'normal' (?var=value) format, or PATH (/var/value), they are toggled in a config file. That's why links in Yii are constructed using Chtml::link() with an array of $_GET variables. – Sebastian Dec 07 '11 at 10:01
  • Oh ! So I can... give the whole $_GET array as an input parameter, after unsetting one value :). [leaves for a minute to try it]. – Sebastian Dec 07 '11 at 10:09
  • @Sebastian This could be easily re-worked to use it in `/var/value` format - the exact details of how it would be done depend on the situation, but in effect you are just reformatting strings from the input data, so it's not that difficult. You can just do something like `foreach ($get as $key => val) $myUrl .= "/$key/$val";` (may need slight alteration depending on exactly how your URLs are formatted). – DaveRandom Dec 07 '11 at 10:21
  • elegant trick with the "/$key/$val"! Another solution: `Yii::app()->createUrl(Yii::app()->controller->getId().'/'.Yii::app()->controller->getAction()->getId(), $_GET );` seems to work (after unsetting `$_GET['lg']` :)! – Sebastian Dec 07 '11 at 10:59
  • No need to write code that Yii already provides. Read this: http://www.yiiframework.com/doc/api/1.1/CHttpRequest – marcovtwout Mar 17 '14 at 17:06
5

So, you may use

Yii::app()->getBaseUrl(true)

to get an Absolute webroot url, and strip the http[s]://

1
$validar= Yii::app()->request->getParam('id');
1

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.

Ben
  • 126
  • 7
  • Relying on one particular url style is bad and unnessecary. See this topic about creating url's in general: yiiframework.com/doc/guide/1.1/en/topics.url#creating-urls – marcovtwout Mar 17 '14 at 17:08
0

Yii2

Url::current([], true);

or

Url::current();
Ganesh Patel
  • 67
  • 1
  • 4
0

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

Syakur Rahman
  • 2,056
  • 32
  • 40
0

For Yii1

I find it a clean way to first get the current route from the CUrlManager, and then use that route again to build the new url. This way you don't 'see' the baseUrl of the app, see the examples below.

Example with a controller/action:

GET /app/customer/index/?random=param
$route = Yii::app()->urlManager->parseUrl(Yii::app()->request);
var_dump($route); // string 'customer/index' (length=14)
$new = Yii::app()->urlManager->createUrl($route, array('new' => 'param'));
var_dump($new); // string '/app/customer/index?new=param' (length=29)

Example with a module/controller/action:

GET /app/order/product/admin/?random=param
$route = Yii::app()->urlManager->parseUrl(Yii::app()->request);
var_dump($route); // string 'order/product/admin' (length=19)
$new = Yii::app()->urlManager->createUrl($route, array('new' => 'param'));
var_dump($new); string '/app/order/product/admin?new=param' (length=34)

This works only if your urls are covered perfectly by the rules of CUrlManager :)

Piemol
  • 857
  • 8
  • 17
0

For Yii2

I was rather surprised that the correct answer for Yii2 was in none of the responses.

The answer I use is:

Url::to(['']),

You can also use:

Url::to()

...but I think the first version makes it more obvious that your intention is to generate a url with the curent request route. (i.e. "/index.php?admin%2Findex" if you happened to be running from the actionIndex() in the AdminController.

You can get an absolute route with the schema and domain by passing true as a second parameter, so:

Url::to([''], true)

...would return something like "https://your.site.domain/index.php?admin%2Findex" instead.

-1

Try to use this variant:

<?php echo Yii::app()->createAbsoluteUrl('your_yii_application/?lg=pl', array('id'=>$model->id));?>

It is the easiest way, I guess.

  • 1
    Hardcoding the url is a bad practise. See this topic about creating url's in general: http://www.yiiframework.com/doc/guide/1.1/en/topics.url#creating-urls – marcovtwout Mar 17 '14 at 17:07
-1

Most of the answers are wrong.

The Question is to get url without some query param .

Here is the function that works. It does more things actually. You can remove the param that you don't want and you can add or modify an existing one.

/**
 * Function merges the query string values with the given array and returns the new URL
 * @param string $route
 * @param array $mergeQueryVars
 * @param array $removeQueryVars
 * @return string
 */
public static function getUpdatedUrl($route = '', $mergeQueryVars = [], $removeQueryVars = [])
{
    $currentParams = $request = Yii::$app->request->getQueryParams();

    foreach($mergeQueryVars as $key=> $value)
    {
        $currentParams[$key] = $value;
    }

    foreach($removeQueryVars as $queryVar)
    {
        unset($currentParams[$queryVar]);
    }

    $currentParams[0] = $route == '' ? Yii::$app->controller->getRoute() : $route;

    return Yii::$app->urlManager->createUrl($currentParams);

}

usage:

ClassName:: getUpdatedUrl('',[],['remove_this1','remove_this2'])

This will remove query params 'remove_this1' and 'remove_this2' from URL and return you the new URL

Codeformer
  • 2,060
  • 9
  • 28
  • 46
-1
echo Yii::$app->request->url;
nageen nayak
  • 1,262
  • 2
  • 18
  • 28