What's a good way to handle post data in Codeigniter? - php

I.e. would you recommend me to use one controller method like this:
function save()
{
if(!is_bool($this->input->post('')))
{
$post_data = $this->input->post('');
$this->mymodel->save($post_data);
}
$this->load->view('myview');
}
Or would you recommend writing it using two methods?
function save()
{
if(!is_bool($this->input->post('')))
{
$post_data = $this->input->post('');
$this->mymodel->save($post_data);
}
redirect('controller/method2')
}
The redirect is the crucial difference here. It prohibits resubmissions from update for example.
How do you do it? Is there another better way?

You should always redirect on a successful form post.

You should always redirect on a successful form post.
Absolutely. For anyone wondering why this is the case, here are a couple of the reasons:
Avoid "duplicate submissions". Ever had that when you innocently click refresh or hit the back button and wham, everything has resubmitted?
Being friendly to bookmarks. If your user bookmarks the page, presumably you want them to return where they created it, rather than a blank form (a redirect makes them bookmark the confirmation/landing page.
Further reading:
http://en.wikipedia.org/wiki/Post/Redirect/Get

As Aren B said, redirection is a good idea, but what I would change in your code is that validation of the post data should be done with the form validation functionallity. It is not only more reauseable but the code will get shorter.
If you want to handle AJAX requests, you would need to return something else than a via or a redirection.

Related

how can i get rid of confirm form resubmission in HTML/PHP? [duplicate]

Page one contains an HTML form. Page two - the code that handles the submitted data.
The form in page one gets submitted. The browser gets redirected to page two. Page two handles the submitted data.
At this point, if page two gets refreshed, a "Confirm Form Resubmission" alert pops up.
Can this be prevented?
There are 2 approaches people used to take here:
Method 1: Use AJAX + Redirect
This way you post your form in the background using JQuery or something similar to Page2, while the user still sees page1 displayed. Upon successful posting, you redirect the browser to Page2.
Method 2: Post + Redirect to self
This is a common technique on forums. Form on Page1 posts the data to Page2, Page2 processes the data and does what needs to be done, and then it does a HTTP redirect on itself. This way the last "action" the browser remembers is a simple GET on page2, so the form is not being resubmitted upon F5.
You need to use PRG - Post/Redirect/Get pattern and you have just implemented the P of PRG. You need to Redirect. (Now days you do not need redirection at all. See this)
PRG is a web development design pattern that prevents some duplicate form submissions which means, Submit form (Post Request 1) -> Redirect -> Get (Request 2)
Under the hood
Redirect status code - HTTP 1.0 with HTTP 302 or HTTP 1.1 with HTTP 303
An HTTP response with redirect 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 redirect status code is 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.
Double Submit Problem
Post/Redirect/Get Solution
Source
Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:
Prevent Back button from showing POST confirmation alert
Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.
Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.
The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.
There are two parts to the answer:
Ensure duplicate posts don't mess with your data on the server side. To do this, embed a unique identifier in the post so that you can reject subsequent requests server side. This pattern is called Idempotent Receiver in messaging terms.
Ensure the user isn't bothered by the possibility of duplicate submits by both
redirecting to a GET after the POST (POST redirect GET pattern)
disabling the button using javascript
Nothing you do under 2. will totally prevent duplicate submits. People can click very fast and hackers can post anyway. You always need 1. if you want to be absolutely sure there are no duplicates.
You can use replaceState method of JQuery:
<script>
$(document).ready(function(){
window.history.replaceState('','',window.location.href)
});
</script>
This is the most elegant way to prevent data again after submission due to post back.
Hope this helps.
If you refresh a page with POST data, the browser will confirm your resubmission. If you use GET data, the message will not be displayed. You could also have the second page, after saving the submission, redirect to a third page with no data.
Well I found nobody mentioned this trick.
Without redirection, you can still prevent the form confirmation when refresh.
By default, form code is like this:
<form method="post" action="test.php">
now, change it to
<form method="post" action="test.php?nonsense=1">
You will see the magic.
I guess its because browsers won't trigger the confirmation alert popup if it gets a GET method (query string) in the url.
The PRG pattern can only prevent the resubmission caused by page refreshing. This is not a 100% safe measure.
Usually, I will take actions below to prevent resubmission:
Client Side - Use javascript to prevent duplicate clicks on a button which will trigger form submission. You can just disable the button after the first click.
Server Side - I will calculate a hash on the submitted parameters and save that hash in session or database, so when the duplicated submission was received we can detect the duplication then proper response to the client. However, you can manage to generate a hash at the client side.
In most of the occasions, these measures can help to prevent resubmission.
I really like #Angelin's answer. But if you're dealing with some legacy code where this is not practical, this technique might work for you.
At the top of the file
// Protect against resubmits
if (empty($_POST)) {
$_POST['last_pos_sub'] = time();
} else {
if (isset($_POST['last_pos_sub'])){
if ($_POST['last_pos_sub'] == $_SESSION['curr_pos_sub']) {
redirect back to the file so POST data is not preserved
}
$_SESSION['curr_pos_sub'] = $_POST['last_pos_sub'];
}
}
Then at the end of the form, stick in last_pos_sub as follows:
<input type="hidden" name="last_pos_sub" value=<?php echo $_POST['last_pos_sub']; ?>>
Try tris:
function prevent_multi_submit($excl = "validator") {
$string = "";
foreach ($_POST as $key => $val) {
// this test is to exclude a single variable, f.e. a captcha value
if ($key != $excl) {
$string .= $key . $val;
}
}
if (isset($_SESSION['last'])) {
if ($_SESSION['last'] === md5($string)) {
return false;
} else {
$_SESSION['last'] = md5($string);
return true;
}
} else {
$_SESSION['last'] = md5($string);
return true;
}
}
How to use / example:
if (isset($_POST)) {
if ($_POST['field'] != "") { // place here the form validation and other controls
if (prevent_multi_submit()) { // use the function before you call the database or etc
mysql_query("INSERT INTO table..."); // or send a mail like...
mail($mailto, $sub, $body); // etc
} else {
echo "The form is already processed";
}
} else {
// your error about invalid fields
}
}
Font: https://www.tutdepot.com/prevent-multiple-form-submission/
use js to prevent add data:
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

Laravel : Load a view after posting

In Codeigniter I used to call the view function after posting data. Like below;
Ex: I have a show_products() function which will display list of products. When a user add a new product I'm posting data into add_product() function. If the process is successful I will not redirect to the products page, instead load the display function inside the add_product() like this:
//Inside the add_product() function
if(success){
$this->show_products();
}
I think, there is no point of reloading the page again. Since we are already in the post function we can straight away set the view after the database insert.
However in laravel I see people redirecting after posting data.
ex:
//Inside the postProduct() function
if(success){
return Redirect::to('products');
}
I tried;
//Inside the postProduct() function
if(success){
$this->getIndex();// this is my product display function
}
but it didn't work.
Do we have a benefit by loading the view in the post function without redirecting every time?
If so how can I achieve the same thing with the laravel?
Thanks a lot!
It's not about the Laravel, instead, it's about a good or right way of doing things. In other words, it's a good programming practice to redirect to another route/page after you successfully submit a form.
Even in CodeIgniter or plain Php I do like this approach and encourage other developers to do that. So, the question is why this redirect is better than directly calling another method from the same request to show another view/page ?
This is the life cycle of the process:
You post a form to a route/action page.
You validate the submitted data and upon successful validation you insert the submitted data in to your database, otherwise you redirect back to that form with errors and old user inputs.
So. assume that, you have submitted a form and done saving the data into database successfully. After you save it you done something like this:
return View::make('...')->with('success', 'Data saved!');
In this case, your user can see the success message on the screen but what if the user, presses the f5 key from the keyboard to refresh the page (probably, accidentally), the form will be submitted to the same action again and the whole process will be repeated again.
So, if you had a redirect after form submission then, refreshing the page won't make any request to that form again.
Google search result on form resubmit on refresh., check the links, may be first one/two, you'll get better idea about the problem and the benefits of redirection after form submission.
in Codeigniter to redirect page we have redirect() function.
if(success){
redirect('products');
}
You don't have to return Redirect. The reason people use it quite often in larvel is because it's comfy.
You can return something else, eg. a view:
return View::make('home.index')->with('var',$var);
In Laravel, to redirect after doing a POST, you could return a redirect with a named route:
return redirect()->route('my-route-name');
Or if you are within the controller that has the route method you want (eg. the index method, you could do this as well:
return self::index();

HTML forms and how they keep user input

I am working on a basic HTML/PHP form for user registration. It works fine but have a problem I would like to solve. I've noticed that during testing that when I press submit and the passwords don't match, I'm taking to the error page (by design), then redirected back to registration where I have to enter everything all over again. Is there a way to keep the fields populated with the user's input so that they can just go back and correct what needs to be fixed instead of having to re-enter everything all over again?
Best way would be to use AJAX so they never have to leave the page in the first place.
Failing that, using history.back() to send the user back should keep the form info there.
Failing that, save their form data in a $_SESSION variable and use that to repopulate the form.
You can save submitted data in session:
-Init a php session by <?php session_start(); ?>, this function must appear BEFORE the tag
-store a variable in session like this: $_SESSION['myVar']=$myVar;
-retrieve it back (in another page) by : $myVarFromSession = $_SESSION['myVar'];
-Finally, destroy the session and its content : <?php session_destroy(); ?>
Quick — Dirty
Send back the username/password in a query string (?username=...&password=...)
Set SESSION variables before redirecting
Better — Encapsulate Logic into Classes
I strongly recommend encapsulating your various moving parts in classes that handle the request, form, validation, error message, and rendering/routing logic. You will find this infinitely easier than trying to manually throw error messages/data back and forth between scripts. If your site/app is big, or if you want to follow best practices and become a better developer, classes are the way to go.
Take a look at how different frameworks handle this problem. Some good ones are Yii, Laravel, and Symfony2. Right out of the box they'd be able to quickly and easily solve this problem.
Sample Code
class LoginForm
{
public $password;
public $username;
public function validate()
{
// Perform validation
}
}
class HttpRequest
{
public function getIsPostRequest()
{
return 'POST' === $_SERVER['REQUEST_METHOD'];
}
public function getPost($name, $default=null)
{
return isset($_POST[$name]) ? $_POST[$name] : $default;
}
}
// This code processes the request to your login page.
// View::renderFile() renders a "view", which is a mix
// of HTML/PHP code that gets served back to the browser.
$request = new HttpRequest();
$form = new LoginForm();
if ($request->getIsPostRequest()) {
$form->username = $request->getPost('username');
$form->password = $request->getPost('password');
if ($form->validate()) {
// Login the user...
}
}
View::renderFile('login.php', array(
'form' =>$form,
));
Storing the user's password in the session or passing it in the query parameters is a security no-no. You should display the error on the same form page to avoid redirecting and losing that data. That way the error is still displayed and the script still has the user's input data from the $_POST. Of course, Dan Schmidt's recommendation to use a framework is excellent. The purpose of the framework is to save you from the headache you're experiencing right now.
If you insist on redirecting to an error page, then you can store the username in the session, but I highly recommend against storing the password as mentioned before.

Handling forms that are on every page in CodeIgniter

The way I made it work is create a dedicated controller that handles my forms that repeat on multiple pages i.e. somedomain.com/form/callmeback/ and so far so good. However, once the validator has done its thing I need to either return to the page from which the form was submitted, with a list of errors to display or send the message and then return to the originating form page with a success message.
What would be the "best" way to accomplish that?
So far my thoughts are lingering on using $_SERVER['HTTP_REFERER'] or a hidden field with a current_url() as its value, and then just do header('Location:'.$_POST['ref']) but that would not allow me to post back validation errors.
[EDIT]
In the end I've solved my problem using codeIgniter session flash data functionality
//redirect back to source
if($_SERVER['HTTP_REFERER'] && strpos($_SERVER['HTTP_REFERER'], base_url()) !== false) {
//do form handling stuff here
$this->session->set_flashdata('callmeback_errors', validation_errors());
header('Location:' . $_SERVER['HTTP_REFERER']);
} else {
//invalid referer, do nothing say nothing, pretend the page doesn't exist
show_404();
}
thanks for your ideas :)
Flash session is a good idea but i m not sure if it will be working properly with validation_errors() function,
but i have a different thought, what about instead of dedicated controller and dedicated helper that do the same functionality including so you wont have to change the controller and just send the POST array to helper function, hope this helps
Serialize your errors to the session and then remove them on the next request like "flash" message. Ive done similar before with Symfony.

Prevent form resubmit in Zend framework?

An action within a controller generates the next id from the database and displays it on screen as reference. How can I prevent the action being called again if the user clicks refresh.
The post-redirect-get pattern with Zend Framework would generally involve leaving the action of the form empty (so it posts to itself) and then redirecting when you don't want to display the form again (so upon success).
public function newAction() {
$form = new Form_Foo();
if($this->_request->isPost()) {
if($form->isValid($this->_request->getPost()) {
//save or whatever
return $this->_redirect('path/to/success');
}
// else fall through
}
$this->view->form = $form;
}
if ($this->isPost()) {
// Check validation
if ($error) {
$dataToMove = array();
// $dataToMove is array that you want to pass with redirect
// It can be an array of errors or form data that user has entered
// Use FlashMessenger helper to pass data to redirection via Zend_Session
$this->_helper->getHelper('FlashMessenger')->addMessage($dataToMove);
// And redirect page to form url
$this->_helper->getHelper('Redirector')->goToUrl('/form/url/');
}
// If not posted, get data from FlashMessenger
$data = $this->_helper->getHelper('FlashMessenger')->getMessages();
// And assign to view or make that you want
$this->view->formData = $data;
Although this is older post people still come here for answers, so let me help a bit more.
Redirecting form is great and useful but we are still not preventing peple from clicking back button and resubmitting that way.
The solution is to either show the form as popup and make it disapear when done (easily done with jquery) or generate unique id for each transaction and checking if id was previously used.
See article: http://www.boutell.com/newfaq/creating/stoprefresh.html
Hope it helps.
You can do this by implementing a 302 redirect
header('HTTP/1.1 302 Found');
header('Location: displayId.php?id=5');
die();
Assuming you have these pages
form.php
processForm.php
displayId.php
Form.php only displays form and sends data via POST to processForm.php.
Within processForm.php you can parse data and issue the redirect to displayId.php with id you want to display in GET parameter.
This way when user refreshes the page (displayId.php) the form data is not processed again.
I know you're trying to do this in Zend Framework but I'm just saying I'm after the same functionality. Just moved everything to ZF and I'm quite disappointed to see that this functionality isn't built in.
I used to have every form submit to process.php which processed all GET, POST requests and then saved the results (like error and success messages) and redirected you to the new place.
If $_SESSION['post_data'] was set, I would $_POST = $_SESSION['post_data']; and then remove it from the session.
This worked great but now I'm gonna need the same in ZF :D As I say... a little disappointed as I don't believe ANYONE wants a dialog to appear asking about resubmitting data.. what the hell does that mean to your enduser? nothing!

Categories