Gianni
Gianni

Reputation: 136

why does php fom submission keeps submitting every time I refresh?

So I submit my form and and every time I click ctrl-r it refreshes the page without alerting me it will resubmit the form. Every time I click the reload button on browser it asks me that it will reload but I already submitted the form so now I am getting a new submit every time and creating a new item in my sqlDB. I refresh and I do not know what I have to do to automatically refresh the page to where it wont save the form resubmit and is like a new page again.

where the //end else is at is where I have tried adding a header(Location:) but I get an error. I posted the error more to the bottom of the question.

footer.php

<?php
if(isset($_POST['submit-story'])){

    $answer = $_POST['human-story'];

    if (!ctype_digit($answer) == 8) {
      echo "Cannot store event. wrong answer";
      die();      
    } else {
    //Get the uploaded file information
    $name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
    //get the file extension of the file
    $type_of_uploaded_file =
        substr($name_of_uploaded_file,
        strrpos($name_of_uploaded_file, '.') + 1);

    $size_of_uploaded_file =
    $_FILES["uploaded_file"]["size"]/1024;//size in KBs

    //Settings
    $max_allowed_file_size = 1000000; // size in KB
    $allowed_extensions = array("jpg","jpeg","gif","bmp","mp4", "mov");

    //Validations
    if($size_of_uploaded_file > $max_allowed_file_size )
    {
      $errors = "\n Size of file should be less than $max_allowed_file_size";
    }

    //------ Validate the file extension -----
    $allowed_ext = false;
    for($i=0; $i<sizeof($allowed_extensions); $i++)
    {
      if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
      {
        $allowed_ext = true;
      }
    }

    if(!$allowed_ext)
    {
      $errors = "\n The uploaded file is not supported file type. ".
      "Only the following file types are supported: ".implode(',',$allowed_extensions);
    }

    //copy the temp. uploaded file to uploads folder
      $upload_folder = 'uploads/';
      $to = "[email protected]"; // this is your Email address
      $first_name = filter_var($_POST['first_name']. $schoolOfficialShortName, FILTER_SANITIZE_STRING);
      $story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
      $eventDate = filter_var($_POST['eventDate'],FILTER_SANITIZE_STRING);
      $eventLocation = filter_var($_POST['eventLocation'],FILTER_SANITIZE_STRING);
      $subject = "blah-" . $schoolOfficialShortName . "Event";
      $title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
      $message = $first_name . " wrote the following:" . "\n\n" . $title ."<br>". $story;
      $headers = "From: $first_name";
      // boundary
      $semi_rand = md5(time());
      $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
      // headers for attachment
      $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
      // multipart boundary
      $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
      $message .= "--{$mime_boundary}\n";
      $content = '';
      $tmp_path = $_FILES["uploaded_file"]["tmp_name"];
        if($tmp_path) {
          $filename = $_FILES["uploaded_file"]["name"];
          $path_of_uploaded_file = $upload_folder . $filename;
          if(!copy($tmp_path, $path_of_uploaded_file))
          {
            $errors = '\n error while copying the uploaded file';
          }
          $file_size = filesize($path_of_uploaded_file);
          $handle = fopen($path_of_uploaded_file, "rb");
          $content = fread($handle, $file_size);
          fclose($handle);
          $content = chunk_split(base64_encode($content));
        }
        // if attachment has successfully encoded
        if ($content) {
        $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"{$filename}\"\n" .
        "Content-Disposition: attachment;\n" . " filename=\"{$filename}\"\n" .
        "Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
        $message .= "--{$mime_boundary}\n";
        }
        $headers2 = "From:" . $to;
        mail($to, $subject, $message, $headers);
        //send items to S3 bucket
        move_uploaded_file($upload_folder, $filename);

        //store image to s3 bucket
        try {
            $result = $s3->putObject([
              'Bucket' => $config['s3']['bucket'],
              'Key' => "uploads/{$name_of_uploaded_file}",
              'Body' => fopen($path_of_uploaded_file, 'rb'),
              'ACL' => 'public-read'
            ]);

            $results = $result['ObjectURL'];

            if (is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
                  //inserts in pending table
                  $sql = "INSERT INTO items (photo,title,eventDate,description,name,pLike,pDislike,address) VALUES ( :photo, :title, :eventDate, :description, :name, :pLike, :pDislike, :address)";
                  $stmt = $pdo->prepare($sql); 
                  $stmt->bindParam(':title', $title);
                  $stmt->bindParam(':photo', $results);
                  $stmt->bindParam(':description', $story);
                  $stmt->bindParam(':eventDate', $eventDate);
                  $stmt->bindParam(':address', $eventLocation);
                  $stmt->bindParam(':name', $first_name);
                  $stmt->bindValue(':pLike', 0, PDO::PARAM_INT);
                  $stmt->bindValue(':pDislike', 0, PDO::PARAM_INT);
                  $stmt->execute();       
                }else {
                  die("<h1>There was an error. Please go back and retry.</h1>");        
                } 
                //remove the pending file in uploads folder
                unlink($path_of_uploaded_file);

        } catch(PDOException $e){
            echo 'error in query:  '.$e->getMessage();
        }
      };// end else 
};// end isset final
?>

I have tried adding a header(Location: index.php) But i get a weird error saying

Cannot modify header information - headers already sent by (output started at /Users/mine/Documents/www/website/schools/inc/header.php:67) in /Users/mine/Documents/www/website/schools/inc/footer.php on line 127

Upvotes: 0

Views: 95

Answers (2)

Jakir Hossain
Jakir Hossain

Reputation: 2517

You can not use header() once text has been output to the browser. As your header file include presumably outputs HTML, header() cannot be used.

You can solve this in flowing ways:

  1. Move the if statement above the header file include.
  2. ob_start() at the top of the script to buffer the output.

Upvotes: 1

Martin Hrabal
Martin Hrabal

Reputation: 102

  1. Unset $_POST variable after proccessing data in your footer.php

  2. your header already send problem : It means some text was already outputted. Place your header() on top of your script. Or look at the ob_start and ob_end_clean() functions.

Upvotes: 1

Related Questions