4

I previously used to always write $this->load->view() to load a view. I noticed that there is a problem with that especially when it comes to resubmission and URL in address bar. Instead I started using redirect('controller/function','refresh') to achieve the same thing. My question is: Is this an alright approach or is it frowned upon? I feel my code is much smoother this way but I would certainly like to know if this had any side effects later.

e.g. use case:

$id = $this->user_model->buildAccount($name, $email);

if(isset($id) && $id != '') {
    $this->session->set_userdata('id', $id);
    redirect('users/details');
} else {
    redirect('members/');
}
Touki
  • 7,465
  • 3
  • 41
  • 63
spacemonkey
  • 2,530
  • 6
  • 23
  • 27

2 Answers2

3

When it comes to CI any approach you take is okay, imho, your approach is just fine. In your code above where you redirect the user after creating session, you should also check for the validity of the session in your user/details function. Anyways, you have to call load->view() to load a view, be it in any function. So, doesn't matters where you load your view.

Nil'z
  • 7,487
  • 1
  • 18
  • 28
  • Yes I do constantly check for sessions and tokens to ensure authenticated access to all parts of the site. It is great of you to share your opinion. Thanks mate – spacemonkey Oct 17 '13 at 07:30
  • Happie to help :D. Consider accepting the answer if it helped you. @spacemonkey – Nil'z Oct 17 '13 at 07:34
2

You need to use PRG - Post/Redirect/Get pattern. Redirect and load view aren't the same if you have the form in the content of the page.

Scenario:

There is a view, view_1 with form in it to debit money from a account. After submission of the form in the view_1 you want to jump to view_2 with a success message and you have 2 options to achieve the same. 1. load view_2 with success message or 2. redirect to view_2 with flash data carrying success message.

Option 1: load view_2 with success message When you submit the form and refresh, it will cause resubmission and cause multiple debit from the account, which shouldn't be the case. You too can see the alert popping od "Confirmation of form resubmission".

Option 2: This is the right answer PRG

PRG - Post/Redirect/Get PRG is a web development design pattern that prevents some duplicate form submissions which means, Submit form (view_1) -> Redirect -> Get (view_2)

Under the hood

An HTTP response with this status code will additionally provide a URL in the location header field. The user agent (e.g. a web browser) is invited by a response with this code to make a second, otherwise identical, request to the new URL specified in the location field.

The HTTP 1.0 with HTTP 302 or HTTP 1.1 with HTTP 303 ("See other") response code to ensure that in this situation, the web user's browser can safely refresh the server response without causing the initial HTTP POST request to be resubmitted.

Source

Angelin Nadar
  • 8,944
  • 10
  • 43
  • 53