[php] Get current URL/URI without some of $_GET variables

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 
);

This question is related to php frameworks uri yii current-page

The answer is


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.


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

Yii2

Url::current([], true);

or

Url::current();

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


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


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


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.


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


So, you may use

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

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


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

You are definitely searching for this

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

echo Yii::$app->request->url;

Yii 1

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

For Yii2:

Yii::$app->request->url

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.


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

This will output something in the following format:

http://www.yoursite.com/your_yii_application/

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to frameworks

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Vue.js—Difference between v-model and v-bind OS X Framework Library not loaded: 'Image not found' How to get root directory in yii2 Laravel blank white screen Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies How to filter (key, value) with ng-repeat in AngularJs? Microsoft .NET 3.5 Full download Using CSS in Laravel views? Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

Examples related to uri

Get Path from another app (WhatsApp) What is the difference between resource and endpoint? Convert a file path to Uri in Android How do I delete files programmatically on Android? java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder How to get id from URL in codeigniter? Get real path from URI, Android KitKat new storage access framework Use URI builder in Android or create URL with variables Converting of Uri to String How are parameters sent in an HTTP POST request?

Examples related to yii

Only on Firefox "Loading failed for the <script> with source" Stupid error: Failed to load resource: net::ERR_CACHE_MISS Yii2 data provider default sorting Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in CURL ERROR: Recv failure: Connection reset by peer - PHP Curl findAll() in yii Get current URL/URI without some of $_GET variables Include CSS,javascript file in Yii Framework

Examples related to current-page

Get current URL/URI without some of $_GET variables