title: Yii. Checking url before redirecting to prevent attack
body: <p>I have <strong>$returnUrl</strong> var from <strong>Form</strong> with controller/action in it:</p>
  
  <pre><code>&lt;?=CHtml::hiddenField('returnUrl', 
      Yii::app()-&gt;urlManager-&gt;parseUrl(Yii::app()-&gt;request)
  );?&gt;
  </code></pre>
  
  <p>In controller i have something like this:</p>
  
  <pre><code>$returnUrl = Yii::app()-&gt;request-&gt;getPost('returnUrl');
  $returnUrl = array($returnUrl);
  $this-&gt;redirect($returnUrl);
  </code></pre>
  
  <p>But it also work then i change <strong>$returnUrl</strong> from <strong>controller/action</strong> to external site url. Ex: if i put <strong><a href="http://google.com" rel="nofollow">http://google.com</a></strong> to <strong>$_POST['returnUrl']</strong> instead of <strong>site/index</strong> yii redirect me to <strong>/<a href="http://google.com" rel="nofollow">http://google.com</a></strong> without any errors.</p>
  
  <p>What is the best way to check <strong>$returnUrl</strong> before redirecting? How i can compare <strong>$returnUrl</strong> with my routes or controllers/actions?</p>
  
  <p>Now i do next:</p>
  
  <pre><code>$returnUrl = Utils::sanitizeReturnUrl($returnUrl);    
  ...
  class Utils 
  {
      public static function sanitizeReturnUrl($returnUrl)
      {
          if (!preg_match('~^([-a-z0-9_]+|[-a-z0-9_]+/[-a-z0-9_]+)+$~i', $returnUrl))
          {
              $returnUrl = Yii::app()-&gt;homeUrl;
          }
  
          return $returnUrl;
      }
   }
  </code></pre>
  
  <p>But may be exists more appropriate way</p>