PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 20, 2022

[FIXED] Yii User-friendly url and keep the old get format working

 January 20, 2022     php, yii, yii-url-manager, yii2     No comments   

Issue

I set to the main config the following url rules:

    'urlManager'=>array(
        'urlFormat'=>'path',
        'showScriptName'=>false,
        'rules'=>array(
            '<controller:\w+>'=>'<controller>/list',
            '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            '<controller:\w+>/<id:\d+>/<title>'=>'<controller>/view',
            '<controller:\w+>/<id:\d+>'=>'<controller>/view',
            '\?r=<controller:\w+>/<action:\w+>' => '<controller>/<action>'
        ),
    ),

Everything is woking fine, but I also want the previous url format to keep working so I don't have to rewrite lots of urls that I don't care it to be seo-friendly:

index.php?r=controller/action&param1=value1

But it shows an error now. Is there a way to keep it working?


Solution

To my opinion the best way is to replace all old urls with your IDE regex replace option. But anyway you can do what you want this way:

  1. Use following route rule in the urlManager config: 'rules' => [ [ 'class' => 'my\namespace\UrlRule', 'pattern' => '<controller>/<action>', 'route' => '<controller>/<action>', ], ...

  2. Extend yii\web\UrlRule with your my\namespace\UrlRule and rewrite its 'parseRequest' method so that it could use $_GET['r'] parameter value if is set:

    namespace my\namespace;

    class UrlRule extends \yii\web\UrlRule
    {
        public function parseRequest($manager, $request)
        {
            if ($pathInfo = \Yii::$app->request->get('r')) {
                \Yii::$app->request->setPathInfo($pathInfo);
            }
            return parent::parseRequest($manager, $request);
        }
    }

You may also extend yii\web\Request instead so that it's 'getPathInfo' method could use $_GET['r'] parameter if set.



Answered By - Pavel Bariev
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing