PHP Codeigniter ; Preventing form resubmit

12,160

Solution 1

Try redirect to itself

public function find()
{   
    $data['search_result']=$this->search_model->search($this->input->post('search_key'));
    if($this->input->post('search_key')) {
        redirect('yourcontroller/find');
    }
    $this->load->view('template/header');
    $this->load->view('pages/search_result',$data);
    $this->load->view('template/footer');
}

Solution 2

Simple solution is to have a hidden timestamp field in the form.

<?php echo form_hidden( 'TS', time() ); ?> 

When the form is processed, save this timestamp in the session,

$this->session->set_userdata( 'form_TS', $this->input->post( 'TS' ) ); 

Before processing the form check that two timestamps doesn't match

if ( $this->input->post( 'TS' ) != $this->session->userdata('form_TS') ) 
{...} 

Solution 3

IF you want to avoid the resubmit then please after save redirect on same controller like this It can be solved using session. If there is any POST form submit,

ie

if (count($_POST) > 0){
  $this->session->set_userdata('post_data', $_POST );
  redirect('same_controller');
}
else{
  if($this->session->userdata('post_data')){
    $_POST = $this->session->userdata('post_data');
    $this->session->unset_userdata('post_data');
  }
}
Share:
12,160
Chinthu
Author by

Chinthu

Updated on June 26, 2022

Comments

  • Chinthu
    Chinthu almost 2 years

    I am creating a search page in my CodeIgniter project. On submit, the form calls the controller function, data is fetched via model function and the resulting array is passed to the view

    The problem is that when I refresh the result page the form is resubmitting because the $_POST data is still there in the request headers. How can I avoid that resubmit confirmation message

    Following is the code for my form :

    <!--form--> 
    <form id="find" action="<?php echo base_url()?>search/find" method="post">
        <input type="text" name="search_key" class="tb4" id="search_key" placeholder="Search here"/>
        <input type="button" value="search"/>
    </form>
    

    Following is the code for my controller:

     /*
         * function for fetching search results
         * @param void
         * @return void
         */
        public function find()
        {   
            $data['search_result']=$this->search_model->search($this->input->post('search_key'));
            $this->load->view('template/header');
            $this->load->view('pages/search_result',$data);
            $this->load->view('template/footer');
        }
    

    Kindly help me with this.I can't use redirect instead of loading the view since I am bound to pass the result array $data to the view.

  • Pupil
    Pupil over 10 years
    Exactly, redirection will server the job as next time it will not get the form for submitting, well done.