简体   繁体   中英

Redirect not stopping re-submission?

PHP

    $thisfile=$_SERVER["REQUEST_URI"];

    if(isset($_POST['comment'])&&!empty($_POST['comment'])){
    if($id!=0){
    $comment=$_POST['comment'];

    if ($comment_query=mysql_query("INSERT INTO `photosite`.`comments` VALUES ('$id', '', '$firstname', '$surname', '$photo_id', '$comment', '$time')")){

    header('Location: photopage.php?photo_id='.$photo_id.'', true, 303);
    exit;

    }else {
    echo 'Could not add comment';
    }
    }else {
    echo'Please Log In to add a Comment';
    }
    }       

I do not get why my

header('Location: photopage.php?photo_id='.$photo_id.'', true, 303);
    exit;       

Still alowas the user to resubmit data? This links to the same page because it is for adding comments so when a user adds a comment, the page refreshes to the same page. But if you refresh again, the content is re-submitted, any idea why?

UPDATE: I DO have stuff echoed out before all this code in the same document. Is that the problem?

Ok I changed the form action to another page to be processed. There were previous things outputting to the page which was the problem!

Try

...
header('Location: /photopage.php?photo_id='.$photo_id.'', true, 303);
...
 header('Location: photopage.php?photo_id='.$photo_id.'&added='.time());
    exit;

should work. The code you provided should also work. The header->location removes the POST contents, so if you refresh the page afterwards, it should not resubmit.

Pressing the BACK button is a different story, you cannot solve that, unless you are using an unique token for every form request.

Example:

 //check if the token in the session matches the token in the post
 if( isset( $_POST['token'], $_SESSION['token']) 
     && $_SESSION['token'] == $_POST['token'] ){
    //handle your post data
     [...]
 }

 //set the token
 $_SESSION['token'] = sha1(time().mt_rand());

 //process your form
 ?>
 [...]
 <input type='hidden' name='token' value='<?php echo $_SESSION["token"];?>'/>
 [...]

Ok, seems I have find out your problem.. I think Your error reporting is switched off, so You don't see the warning about headers, "Cannot modify header information – headers already sent ...".
You cant send header or modify them, as there are sent, because of that You must turn on buffering. Use ob_start() on the top of Your code. It must look like this

<?php
ob_start();
..

Don't use any whitespaces before <?php .

And remove the parameter true, 303 from Your header function..

header('Location: photopage.php?photo_id='.$photo_id);
exit();

http://www.php.net/manual/en/function.ob-start.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM