How to redirect to Invalid page if wrong URL or wrong controller/action in Yii?

Sajin

How can I redirect to or render an invalid page in my website if the user tried to type in the URL an action in controller that doesn't exist. I wanted a common code for this as I have many controllers in website so that If a user type in action that is wrong or does not exists will redirect to page saying " You are lost or request page did not found"?

Im using Yii framework.

JamesG

When it comes to Controllers and Actions, Yii will do this automatically - if your URL Manager config is set up correctly.

in config/main.php, in the urlmanager section:

'urlManager'=>array(
    'showScriptName' => false,
    'urlFormat'=>'path',
    'useStrictParsing'=>true,
    'rules'=>array(
         // Remove all the default Yii rules

         // Add your own specific rules
    ),
),

Several things here:

  • I'm assuming you're using clean URLs from following the Tutorial
  • useStrictParsing prevents Yii being over generous when trying to match URLs
  • Removing Yii's default generic controller:action route rules means there's no way into your app that you don't specify.

If you're talking about throwing an error within a Controller Action, you can do this using Yii's CException class(es).

public function actionCheckOk()
{
    if($ok)
    {
        $this->render('ok');
    }
    else
    {
        throw new CHttpException(404, 'Page not found');
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related