簡體   English   中英

重定向不停止重新提交?

[英]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';
    }
    }       

我不明白為什么我的

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

還允許用戶重新提交數據嗎? 這鏈接到同一頁面,因為它用於添加評論,因此當用戶添加評論時,頁面將刷新到同一頁面。 但是,如果再次刷新,內容將重新提交,為什么?

更新:我確實在同一文檔中的所有這些代碼之前回盪了一些東西。 那是問題嗎?

好的,我將表單操作更改為另一個要處理的頁面。 有以前的東西輸出到頁面上,這就是問題所在!

嘗試

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

應該管用。 您提供的代碼也應該起作用。 header-> location會刪除POST內容,因此,如果以后刷新頁面,則不應重新提交。

按下BACK按鈕是另一回事,除非您為每個表單請求都使用唯一的令牌,否則您將無法解決該問題。

例:

 //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"];?>'/>
 [...]

好的,似乎我已經找到了您的問題。我認為您的錯誤報告已關閉,因此您不會看到有關標頭的警告,“無法修改標頭信息–標頭已發送...”。
您不能發送標頭或修改標頭,因為已發送標頭,因此必須打開緩沖。 在代碼頂部使用ob_start() 看起來像這樣

<?php
ob_start();
..

<?php之前不要使用任何空格。

並從您的標頭函數中刪除參數true,303。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM