Reputation: 5959
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?
Upvotes: 0
Views: 551
Reputation: 1604
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 (that was false). The general convention is to use $this->getRequest()->getPostData()
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
}
}
Upvotes: 1