2

更新されたデータでページをリロードするフォームがあります。

<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    ...
    <input type="submit" name="Submit" value="Update data">
</form>

ページが更新されたら、「データが更新されました」というメッセージを表示したいと思います。私が信じているリファラーにはこのようなものがありましたが、思い出せません。

ところで私も使用しています:

if (isset($_POST['Submit'])) {
    // prevent resending data
    header("Location: " . $_SERVER['PHP_SELF']);
}

ユーザーが戻るボタンをクリックしたときに迷惑な再送信データメッセージを回避するため。これは正しいです?

4

4 に答える 4

4

If you want to be absolutely sure that a form was submitted, you can store a variable in a session:

session_start();      // at top of page
...
if (isset($_POST['Submit'])) {
    $_SESSION['form_submitted'] = true;
    ...
    // prevent resending data
    header("Location: " . $_SERVER['PHP_SELF']);
}
elseif ($_SESSION['form_submitted'])
{
    ...
}

Less reliable but also possible is the use of $_SERVER['HTTP_REFERER'] to detect what page the visitor came from.

于 2010-05-19T22:09:56.077 に答える
2

You could do something like this ...

a. redirect to self, but with an extra piece of information - "?updated=true" (or **&**updated=true if PHP_SELF already contains a query string)

if (isset($_POST['Submit'])) {
    // prevent resending data
    header("Location: " . $_SERVER['PHP_SELF'] . '?updated=true');
}

b. Based on this extra information, display the text.

if (isset($_GET['updated'])) {
    echo "data updated";
}

... and yes, your redirect is a valid way to prevent resubmision

于 2010-05-19T22:12:53.697 に答える
1

A generally accepted way to prevent the "resend data" message is to use the Post-Redirect-Get pattern.

Ideally you shouldn't be using the same page to display results and also process the form. I would suggest moving "Data updated" to a separate page that you redirect to after the form validation has passed.

This way, the Back button on the browser behaves intuitively for the user without those annoying messages.

Also, technically the $_SERVER "referer" value can be spoofed so you shouldn't always rely on it.

于 2010-05-19T22:09:47.307 に答える
0

使用しているものをほとんど使用できます。

if (isset($_POST['submit'])) {
    echo "data submitted";
}

どうしてそんなことしないの?

于 2010-05-19T22:05:34.167 に答える