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 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法