5

Hi I have a form that adds attachments to a post, however when the form posts it obviously doesn't show the post with the new attachment echoing "your file has been uploaded". When the user refreshes the page (to try and show their new attachment) the form posts again!

Is it possible to either (1) stop the form posting again on refresh, (2) automatically refresh the page to display the post with its new attachment?? (2 is way better)

<?php $post_id = $post->ID;
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$id = media_handle_upload('async-upload', $post_id); //post id of Client Files page
unset($_FILES);
if ( is_wp_error($id) ) {
    $errors['upload_error'] = $id;
    $id = false;
}

if ($errors) {
    echo "<p>There was an error uploading your file.</p>";
} else {
    echo "<p>Your file has been uploaded.</p>";
}
}

?>
<form id="file-form" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST">

<p id="async-upload-wrap"><label for="async-upload">upload</label>
<input type="file" id="async-upload" name="async-upload"> <input type="submit" value="Upload" name="html-upload"></p>

<p><input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" /></p>

<p><input type="submit" value="Save all changes" name="save" style="display: none;"></p>
</form>

Thanks! :)

6

Instead of …

} else {
    echo "<p>Your file has been uploaded.</p>";
}

… redirect to another address on success:

} else {

    $new_url = add_query_arg( 'success', 1, get_permalink() );
    wp_redirect( $new_url, 303 );
    exit;
}

Status code 303 triggers a GET request:

This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

In your form handler check first if $_GET['success'] is set and its value is 1, then print a success message. The visitor can reload this page again and again – and nothing will be sent.

  • Unfortunately that didn't work, and I have no idea why because that php does stick up (just to confirm all I was supposed to do was replace the echo? – ameeromar Apr 20 '13 at 16:40
  • You have to send the header before any output has been sent to the browser. – fuxia Apr 20 '13 at 16:42
  • so put the php code bit in the header? – ameeromar Apr 26 '13 at 13:02
  • 2
    @ameeromar Yes. All data processing should be done before you start creating output. – fuxia Apr 26 '13 at 13:12
1

I had the same problem and it was "complicated" by the fact that I redirect all URLs to a single .php file. It turned out all I had to do to solve it was to insert the following piece of code before any html is written to the page.

<?php
if (isset($_POST['mypostvar']) && isset($_SERVER['REQUEST_URI']))
{
    [process the post data in 'mypostvar']
    header ('Location: ' . $_SERVER['REQUEST_URI']);
    exit();
}
?>

This will redirect to the same page after the postdata is processed as you want it. After the redirect the original postdata is vanished and will not trigger the resubmit. The function 'header()' will only work if you insert it before anything is written to the page. exit() is necessary.

You have to process the post data before you place the header().

0

I solved this my using the template_redirect action (either in a a plugin or on your themes functions.php file).

add_action('template_redirect','myfunction') ;

function myfunction() { 
  global $post;
  $post_id = $post->ID;
  if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
     require_once(ABSPATH . 'wp-admin/includes/admin.php');
     $id = media_handle_upload('async-upload', $post_id); //post id of Client Files page
     unset($_FILES);
     if ( is_wp_error($id) ) {
        $errors['upload_error'] = $id;
        $id = false;
    }

  }
  $error = ($errors) ? 1 : 0;
  wp_redirect( "/?p={$post_id}?errors={$error}",301);
}

Then on your page you can check for errors

if ($_GET['errors']) {
    echo "<p>There was an error uploading your file.</p>";
} else {
    echo "<p>Your file has been uploaded.</p>";
}

(I've not tested this code.. it should give you a good starting point).

  • 1
    With global $post in first line, chances this function works will increase... – gmazzap Sep 12 '13 at 2:40
0

You can also test for $_SERVER['REQUEST_METHOD'] === 'POST' to make sure that the page has been refreshed via POST before processing the form.

if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
   // Do Stuff
}
0

an easier way is to remove the action from your form and have a hidden action so for example:

<html>
<form action="" method="post><input type="text" name="name" />
<input type="submit" value="Submit" />
<input type="hidden" name="action" value="Submit" />
</form>
</html>

have your controller checking for validity and for submissions so to check if the form was submitted:

<?php 
if (isset($_POST['action']) && $_POST['action'] == 'Submit'){
   //you should add code to validate user input here
   //if all ok submit the form
   header('Location: .'); //redirects to the controller without resubmitting
}
?>

this method is very useful for scripts where you are adding or removing records on an admin page as it would reload the page without resubmitting and the record removed or added would be either removed or added to the page :)

0

The best method I found is using javascript and css. Common php redirection method header('Location: http://www.yourdomain.com/url); will work but It cause warning " Warning: Cannot modify header information - headers already sent" in different frameworks and cms like wordpress, drupal etc. So my suggestion is to follow the below code

echo '<style>body{display:none;}</style>'; 
echo '<script>window.location.href = "http://www.siteurl.com/mysuccesspage";</script>'; 
exit;

The style tag is important otherwise the user may feel like page loaded twice. If we use style tag with body display none and then refresh the page , then the user experience will be like same as php header('Location: ....);

I hope this will help :)

0

Basically, the general idea is to redirect the user to some other pages after the form submission which would stop the form resubmission on page refresh but if you need to hold the user in the same page after the form is submitted, you can do it in multiple ways.

Unset Form Data

One way to stop page resubmission on page refresh is to unset the form data after it is submitted so that the variable storing form data becomes empty and wrap up your form processing block of codes to check if the form is empty.

if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
   $data = // processing codes here
   unset $data;
}

This will make $data empty after processing and the first clause would stop form resubmission on page refresh.

Javascript

This method is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.

<script>
if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}
</script>

More on such queries you can visit this link.

-2

the simple and easy way to do this in php. example here:

dont forget the html tags(this form wont allow it here so i use [this])

$firstname = $post[firstname]

$lastname = $post[lastname]

[form action="here.php" method="post"]

first name[input type='firstname' name='firstname']

last name[input type='text' name='lastname']

[input type=submit value=submit]
[/form]

if($firstname==""||$lastname=="")
{

echo"the firstname and lastname are empty";

}
else
{

mysql_query("YOUR DATABASE INSERT HERE");

header("Location:here.php");

}

this is how to keep the data enter in the database from posting the same data twice on page refresh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.