URL not accepting alpha numeric parameter - Yii2-a

2019-02-25 05:42发布

问题:

As soon, i'm passing 41 in URL. confirm.php prints 41.

http://localhost/yii2-app-basic/web/site/confirm/41

But, when i pass "cfeb70c4c627167ee56d6e09b591a3ee" or "41a" in URL,

http://localhost/yii2-app-basic/web/site/confirm/41a

it shows error

NOT FOUND (#404)
Page not found.

The above error occurred while the Web server was processing your request. Please contact us if you think this is a server error. Thank you.

I want to send confirmation id to user to confirm their account. That's why random number "cfeb70c4c627167ee56d6e09b591a3ee" is being passed.

So, what can i do to make URL accept alpha numeric parameter.

config/web.php

'urlManager' => [
      'showScriptName' => false,
      'enablePrettyUrl' => true,
        'enableStrictParsing' => false,
        'rules' => [
            '<controller>/<action>/<id:\d+>' => '<controller>/<action>'
        ],
    ], 

SiteController.php

public function actionConfirm($id)
{
    $id = Yii::$app->request->get('id');
    $this->view->params['customParam'] = $id;

    return $this->render("confirm",array("id"=>$id));
}

回答1:

Change this line

'<controller>/<action>/<id:\d+>' => '<controller>/<action>'

to this

'<controller>/<action>/<id:[a-z0-9]+>' => '<controller>/<action>'

That should do it



回答2:

The current rule states that id is a number(\d+) hence it not working in your examples. Instead of modifying the current rule, I would add one specifically for this case:

'rules' => [
    'site/confirm/<id:\w+>' => 'site/confirm',
    '<controller>/<action>/<id:\d+>' => '<controller>/<action>'
],