doujing1156 2014-01-20 07:22
浏览 43
已采纳

_redirect仍然继续执行php代码

I'm working on custom module and in my IndexController.php I'd written this function to add user to database

public function addAction() {
    if($this->getRequest()->getParam('name', '') == ''){
        $this->_redirect('etech/user');
        //die; or exit;
    }
    $form = $this->getRequest()->getParams();
    $user = Mage::getModel('test/test');
    foreach ($form as $key => $val){
        $user->setData($key, $val);
    }
    try{
        $user->save();
    }catch(Exception $e){
        print_r($e);
    }
    $this->_redirect('etech/user', array('msg'=>'success'));
}

I want to prevent users from accessing this url directly as www.example.com/index.php/etech/user/add/. For this I'd made a check if($this->getRequest()->getParam('name', '') == ''){}. The redirect is working well except the code in there keeps executing and user sees a success message which should not be seen. For this, I'd used old fashioned exit or die to stop executing the code then it doesn't even redirect.

What is the magento way to handle it? Also, as I'm using getRequest()->getParams(), it return both parameters either in get or post. Isn't any way out to get only post parametrs?

  • 写回答

1条回答 默认 最新

  • dongyu4554 2014-01-20 07:27
    关注

    It is correct to use $this->_redirect(), but you must follow it up with a return, ideally return $this;. You could also use exit or die, as you have been doing, but as I'm sure you know it would be better to let Magento do whatever it wants to do before redirecting you.

    As long as you return immediately after $this->_redirect(), you won't have any issues.

    Edit: And as for the request params question, I think you can call something like $this->getRequest()->getPostData() (that was false). The general convention is to use getParams() regardless of whether the data was sent via GET or POST, because technically your code shouldn't be concerned about that.

    Edit #2: If the general convention doesn't apply and you desperately need to restrict access to your page based on POST vs. GET, here's a handy snippet from Mohammad:

    public function addAction()
    {
        if ($this->getRequest()->isPost()) {
            // echo 'post'; do your stuff
        } else {
            // echo 'get'; redirect
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了