Any 'yii' way to get the previous URL?

On most of my pages I have a “back to previous” link. Now the user can actually end up on a page via several different routes. I know I can use standard PHP $_SERVER[‘HTTP_REFERER’] to get the correct URL but I was wondering if Yii includes any method to do this?

Maybe use CWebUser::$returnUrl?

See this extension, it sets the returnUrl automatically.

What I’m after has nothing to do with users/login :)

You can set $returnUrl anywhere and for any reason, it’s not limited to login. Then on your content page, simply do something like:

<a href="<?php echo Yii::app()->user->returnUrl; ?>">Return to previous page</a>

If you want to use the actual referer, you may extend this method:

class HttpRequest extends CHttpRequest


   public function getUrlReferrer($internalOnly = false)


      $referrer = parent::getUrlReferrer();

      if ($internalOnly)


         // Check if $referrer is an internal referer, if not set it to null


      return $referrer;



Now in your view/controller you can check whether Yii::app()->request->getUrlReferrer(true) is null (means not possible to display "return to previous page").

There are some browser that can be instructed to not to send or send a fake referer.

Better follow the first advice of Y!!. You can implement a behaviour for your application, and in beforRequest, for example, you can set the CWebuser::returnUrl (or, if you don’t like this name, you can set wherever you want in the session the return url) and then use this value for the back button.

You can also save an array instead of a single value (in this case you are forced to use something in session, for example a new var named path_in_the_site). You can send a variable with the back button and do something nice like this:

public function beforeRequest()


   if (isset($_GET['back'])) //if has been pressed the back button


        unset Yii::app()->user->path_in_the_site[sizeof(Yii::app()->user->path_in_the_site-1)];  

      // delete the last visited page




       Yii::app()->user->path_in_the_site[]= [...]



This allows you to do more than one back, following backward all the path the user did

Keep in mind, sessions are not “multi-tab-safe”/“multi-window-safe”. Some time ago i’ve written an extension that addresses this problem. It uses a URL parameter to store, where your user came from. Check it out here.

it’s an outdated topic, but you may try this one:


see CHttpRequest

Thanks, it helped me.

For YII2: