开发者

How to redirect from a view in kohana

I have a function called action_reg_user which insert data into the database. I tried doing the usual:

header('Location:page/param1/param2');

But it doesn't开发者_高级运维 work

<?php

if(!empty($_POST)){
    $username = $_POST['uname'];
    $pword = md5($_POST['pword']);
    print_r($_POST);

?>
<a href="reg_user/<?php echo $username; ?>/<?php echo $pword; ?>">Continue Registration</a> 

<?php } ?>


Kohana doesn't generate the request headers until the final page is ready to go back to the browser. If you look in application/bootstrap.php, you'll see this near the very bottom:

echo Request::instance()
    ->execute()
    ->send_headers()
    ->response;

So what you'll want to do is get to the Request object and ask it to do the redirect for you. Usually, this should be done in your controller, not your view. In the controller, you can do $this->request->redirect('kohana/path'). If you insist on doing it in the view, you want Request::current()->redirect('kohana/path') to redirect the currently executing request in the hierarchical chain.

Be careful and notice those are NOT using URL::base in the path- Request::redirect handles that, so you just need to specify the controller/action/parameters.


Try to use

<?php
$this->request->redirect('url/to/redirect/');

Outside actions you can use this code

<?php
Request::initial()->redirect('url');


As your question is tagged Kohana, I assume you are using it.

Kohana is a so called MVC framework. A view should not contain things like redirects and checking $_POST values. It should not contain major logic at all. Views are just meant for presentation.

You should place your redirect in you controller. That is also the place where you should check the $_POST values, and validate them. From the controller, you can pass the $_POST values on to the view.


PHP header("Location: .."); only accepts absolute full URL so simple passing page/param1/param2 won't work.

You need:

header("Location:" . url::base() . "page/param1/param2");

Or even better:

url::redirect('page/param1/param2');


From what i see on your question i assume you are using the header function after you have already output some content.

header() can only be used before any form of output is sent back to the user.

Try placing the header on top before you do the print_r

<?php  
if(!empty($_POST)){
     $username = $_POST['uname'];
     $pword = md5($_POST['pword']);
     action_reg_user($username,$pword);
     if (/* data saved */){
        header('Location: page/param1/param2');  
        exit;
     }
}
?>

and once you set the redirect no other code should run.

I hope this is what you are trying to accomplish :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜