_redirect still continues php code execution - 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?

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
}
}

Related

Laravel allow route to be accessible only from another route

I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.

How to write PHP codes usable both for http and ajax request?

I have some php codes, and there is a condition which declare type of ajax. Now I want to know, should I write all php codes for each request separately? In other word, should I write all php codes twice (almost repeatedly) for both methods?
if(!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest")
{
// I'm ajax
$arr = array('key1'=>'value1', 'key2'=>'value2');
echo json_encode($arr);
} else {
// I'm not ajax
$arr = array('key1'=>'value1', 'key2'=>'value2');
$_SESSION["arr"] = arr;
header('Location: '.$_SERVER['HTTP_REFERER']); // redirect to previous page
}
So, as you see, I have to write all PHP code twice. One time for regular request and one time for ajax request. In reality there is a lot of codes, Maybe 1000 lines of code that I have two write them again for ajax requests (while they are almost identical). Is this a normal way?
Also I want to know, is there any succinct approach? Actually I like to use a approach which needs to php code just one time for both requests ...!
I would create a class to handle those request and put common code right into a method used by both contexts:
// file: class.handler.php
class contextHandler() {
public function handleHttp() {
$this->handleGeneral();
// What ever has to be done in this context
$_SESSION["arr"] = arr;
header('Location: '.$_SERVER['HTTP_REFERER']);
}
public function handleAjax() {
$this->handleGeneral();
// What ever has to be done in this context
echo json_encode($arr);
}
private function handleGeneral() {
// put common code here
$arr = array('key1'=>'value1', 'key2'=>'value2');
}
}
In your code you could then use that class:
include 'class.handler.php';
$handler = new contextHandler();
if(
!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) &&
strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest"
)
{
$handler->handleAjax();
} else {
$handler->handleHttp();
}
This has of course to be adjusted to your concrete needs but offers a nice and clean way of reusing code and generating small and readable code.

Laravel - return a redirectResponse selectively generated in a function

Part of my application is a multi-stage checkout process; during the latter pages of this I first run a sanity check on each request to verify the user actually has some items in their basket: if not they're sent back to the beginning.
I have a controller function like this which is called from multiple routes for DRY purposes.
private function checkBasketFull($request)
{
if (self::isBasketEmpty($request)) {
return redirect('/')->with('status', config('app.empty_basket_message'));
}
}
When I call it, I can't just do:
self::checkBasketFull($request);
because without a return the redirect doesn't fire, only the session data is sent.
And I can't do:
return self::checkBasketFull($request);
because that will give an error if there's no redirect or abort the method if checkBasketFull returns anything else.
My current (working) code is:
$check = self::checkBasketFull($request);
if ($check) {
return $check;
}
Is there an alternative way of writing this on a single line, or modifying the checkBasketFull function, so the redirect will occur if the basket is empty but execution will continue as normal if it isn't?
Either use this:
if ($redirect = self::checkBasketFull($request)) return $redirect;
Or throw an error and catch it in the global error handler.
However, instead of returning and checking that for a redirect like that, I'd much rather keep it as two completely separate methods:
public function someRoute(Request $request)
{
if ($this->isBasketEmpty($request)) return $this->redirectBasketEmpty();
// Continue processing this request...
}
protected function isBasketEmpty(request)
{
// run your login here...
}
protected function redirectBasketEmpty()
{
return redirect('/')->with('status', config('app.empty_basket_message'));
}
Feels cleaner to me.

Protecting a method in CakePHP using POST rather than GET

I want to protect certain methods in my application such as publish, unpublish, and close. By protection I don't mean user authorisation but rather the ability to call the method in a certain way.
I have thought about FORCING the methods to be called using POST rather than GET so that a person can't just paste the URL in the address (even though I could just check the user id of the person doing it). However this means wrapping each button in a different form for each method call.
Alternatively I could use a GUID to allow the GET method but make sure it only allows the correct person to do the function.
Any thoughts ideas on this?
So far I have tried:
function publish($id = null)
{
$post = $this->Post->find('first',array('conditions'=>array('Post.id'=>Tiny::reverseTiny($id))));
if ($this->request->is('post') || $this->request->is('put'))
{
$this->Post->id = $post['Post']['id'];
$this->Post->saveField('status', 1);
$this->Session->setFlash('Your post has been published!');
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id'])));
}
else
{
die('GET METHOD NOT ALLOWED');
}
}
But as stated above that means the link/button for this method would need be in a form containing the action call to this method. And If I have several methods I would need several forms...
Cheers
One way I have thought about is allowing the get method and then checking the user id of the post compared with the logged in user id like so:
if ($this->request->is('get'))
{
if($post['Post']['user_id'] != $this->Auth->user('id'))
{
$this->Session->setFlash('You don\'t have permission to edit that post!');
$this->redirect(array('controller' => 'posts', 'action' => 'index'));
}
else
{
$this->Post->id = $post['Post']['id'];
$this->Post->saveField('status', 1);
$this->Session->setFlash('Your post has been published!');
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id'])));
}
}
Is this good practice?
(Assuming CakePHP 2.0 here)
Firstly, rather than calling die on a Post/Get check. Throw an exception, exceptions in cake are wonderful (Exceptions):
if (!$this->request->is('get')) {
throw new MethodNotAllowedException();
}
Cake also provides a way to generate a link to delete (via post) in your template.
<?php echo $this->Form->postLink('Delete',
array('action' => 'delete', $post['Post']['id']),
array('confirm' => 'Are you sure?'));
?>
Edit (Link): postLink
This is my first answer in a Stack Overflow. Hope it was helpful.
It sounds like you need ACL or some form of permissions if you want to only allow certain users to perform the function. The reason you wouldn't use something like you have posted ( if($post['Post']['user_id'] != $this->Auth->user('id')) ) is because you will end up replicating that code in a lot of functions through out your code base. That is very sloppy.
However, you only want to make sure that the submission was submitted in a specific manner, then the throw error method is the way to go. And you should be able to keep the submission inside the same function like so:
public function publish($id = null) {
if (!$id || !$this->request->is('get') || !$this->request->is('post') || !$this->request->is('put')) {
throw new MethodNotAllowedException();
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->Post->id = $post['Post']['id'];
$this->Post->saveField('status', 1);
$this->Session->setFlash('Your post has been published!');
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id'])));
}
if ($this->request->is('get')) {
// perform your get request here
}
}
With minimal code
$this->request->allowMethod('post');

PHP How to implement flash messages

I'm working on a small custom CMS and would like to implement flash messages. I have searched for hours, but I can't find anything that behaves the way I want. And I can't seem to make anything work.
I want to be able to pass a variable (via $_SESSION) to another page and, on that next request, it will be removed. I want to be able to use a keep_flash function, in case I don't want the message to be removed with the next server request.
Can anyone send me in the right direction? I can't really make anything work.
Thanks.
EDIT: Here is some code I am playing with. It sort-of works. When you first visit the page, it sets the $_SESSION and everything is fine. But if you refresh, now it deletes the $_SESSION. If you refresh again, it adds it back...etc. So, if you were to visit the page, refresh, then go to another page the flash message wouldn't be in the $_SESSION. So how can I fix this?
class flash
{
private $current = array();
private $keep = array();
public function __construct()
{
if (isset($_SESSION['flash'])) {
foreach($_SESSION['flash'] as $k=>$v)
{
$this->current[$k] = $v;
}
}
}
public function __destruct()
{
foreach ($this->current as $k=>$v)
{
if (array_key_exists($k,$this->keep) && $this->keep[$k] == $v) {
// keep flash
$_SESSION['flash'][$k] = $v;
} else {
// delete flash
unset($_SESSION['flash'][$k]);
unset($this->current[$k]);
unset($this->keep[$k]);
}
}
}
public function setFlash($key,$value)
{
$_SESSION['flash'][$key] = $value;
}
public function keepFlash($key)
{
$this->keep[$key] = $this->getFlash($key);
}
public function getFlash($key)
{
if (array_key_exists($key,$this->current)) return $this->current[$key];
return null;
}
}
basic idea is to have script always check specific variable in session (usually called 'flash') for content - if not empty display and delete it from session. When message is needed just place is same variable in session and next check would pick it up....
keep_flash in your case would not proceed with delete, or move to other place based on your needs.
for implementation just google it - usually it wrapped in some kind of class - I personally like phpclasses.org or part of framework

Categories