【问题标题】:How do I obtain the current url without params in Yii?如何在 Yii 中获取没有参数的当前 url?
【发布时间】:2012-01-27 03:46:15
【问题描述】:

我正在使用 Yii。
如果我的网址是http://localhost/evengee/event/page/id/2/sfn+master/?tab=3 我的真实网址(文件路径)只有http://localhost/evengee
我将如何获得,最好在视图中:

  1. 完整网址http://localhost/evengee/event/page/id/2/sfn+master/?tab=3
  2. url不带显式参数http://localhost/evengee/event/page/id/2/sfn+master/

我知道我可以将 str_replace 拆分/分解为 ?并使用 $_SERVER。更愿意使用 Yii 原生方法。

【问题讨论】:

    标签: php url yii url-routing


    【解决方案1】:

    为:

    • 完整 URL (http://localhost/even/page/id/2/?t=3) 使用 Yii::app()->request->getUrl(),

    • 不带参数的 URL(http://localhost/even/page/id/2/ 使用 Yii::app()->request->getPathInfo().

    第二个将为您提供不带架构、服务器和查询字符串的 URL。这似乎已经足够了。

    【讨论】:

    • 我尝试Yii::app()->request->getUrl(),但这没有返回域名。
    • 如果您想要完整的域名,请使用 createAbsoluteUrl。 $this->createAbsoluteUrl( Yii::app()->request->getUrl() );Yii::app()->createAbsoluteUrl( Yii::app()->request->getUrl() );
    【解决方案2】:

    要获取完整的 URL,请使用 CHttpRequestgetRequestUrl() 方法 Yii::app()->request->getRequestUrl();

    可以从CApplication方法中获取当前页面的控制器、模块和动作名称 Yii::app()->getController()->id; //gets you the controller id

    Yii::app()->getController()->getAction()->id; //gets you the action id

    您可以使用 CApplication 的 baseURL 属性拼凑一个 URL

    Yii::app()->baseURL

    【讨论】:

    • CHttpRequest 及其行为没有名为“getRequestUrl”的方法或闭包。那应该是“我”而不是“我”
    • 应该是 Yii::app()->request->getUrl();
    【解决方案3】:

    我发现的最好和更短的方法是:

    Yii::app()->createAbsoluteUrl(Yii::app()->request->getPathInfo());

    $this->createAbsoluteUrl(Yii::app()->request->getPathInfo());

    【讨论】:

      【解决方案4】:

      对于 Yii2,使用\yii\helpers\Url::canonical()

      文档:https://www.yiiframework.com/doc/api/2.0/yii-helpers-baseurl#canonical()-detail

      【讨论】:

      • 这个固件还在开发中吗?问题来自 10 年前
      • 是的。 Yii2 是当前版本。 Yii3 正在积极开发中。 yiiframework.com
      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 2015-09-05
      • 2021-01-16
      • 2014-01-06
      相关资源
      最近更新 更多