Symfony redirect vs forward
I have not read a lot of articles on this but I did a quick Google search and found that all of the few articles I read seems to suggest redirect over forward. But I have a different opinion here, I would suggest that forward is better than redirect in most (if not all) cases.
This is from the Symfony’s documentation (with my emphasis added):
The choice between a redirect or a forward is sometimes tricky. To choose the best solution, keep in mind that a forward is internal to the application and transparent to the user. As far as the user is concerned, the displayed URL is the same as the one requested. In contrast, a redirect is a message to the user’s browser, involving a new request from it and a change in the final resulting URL.
If the action is called from a submitted form with
method="post", you should always do a redirect. The main advantage is that if the user refreshes the resulting page, the form will not be submitted again; in addition, the back button works as expected by displaying the form and not an alert asking the user if he wants to resubmit a POST request.
The first paragraph from the quote above from Symfony’s documentation explains what redirect and foward are. Pretty self explanatory there.
Here, I disagree about the second paragraph. I don’t think that you should always do a redirect for form with “post” method. In fact I’d say, always use forward instead of redirect.
So why use forward instead of redirect?
- You should never rely on browser to not resubmit form data. The main advantage of redirect seems to be that if user refreshes their browser, any form data will not be resubmitted again. But I will say that you should never rely on this. Your code MUST detect and handle situation where the same data is submitted more than once to prevent issues such as duplicate and more seriously, potential security issue like replay attack.
- More secure. Since forward is internal, your users can’t even see it when it happens.
- Ajax friendly. When you update an element via Ajax call, Symfony detects that it is Ajax call and automatically excludes the layout template. But when you use redirect, Symfony can’t even tell if it is an Ajax call or not without additional GET parameter (ugly!).
There are still more reasons for using forward instead of redirect with Symfony (better code, cleaner URL, and more) but I’m really hungry at the moment.
Happy coding! :)