Prevent multi submit PHP

北战南征 提交于 2021-02-20 04:30:27

问题


I am seeking a way to prevent multi form submit. I have a form, for example chat.php and its POST action on different file, eg submitter.php.

I've tried to implement the solution with the unique token using $_SESSION. chat had a unique $_SESSION[token] and submitter had the if $_POST[token]==$_SESSION[token] My problem is that it didn't work if I had multiple windows opened. Guess the application is a chat script where users can chat on multiple windows, like chat.php?user=5, chat.php?user=10 etc)

If users had one window opened, that worked perfectly.

Any ideas?

Code as requested....

chat.php

$_SESSION['token'] = md5(session_id() . microtime());

submitter.php

if($_POST['submg'] == "1") {
    if ($_POST['token'] == $_SESSION['token']) {
     // do stuff
    }
    unset($_SESSION['token']);
}

回答1:


$_SESSION is going to be shared across all open browser windows on a machine. So, if you opened up Firefox, and logged in, every other Firefox window you have open is also logged into that service. What you likely want is a token in the page that gets submitted along with each request (much like a CSRF token) that is unique to the instance of the page. Then, a combination of the $_SESSION variable and the token can be used to identify a particular browser within a particular session.

Edit: Example below.

<?php
session_start();
$instance = null;

if (! array_key_exists('token', $_SESSION)) {
    $_SESSION['token'] = md5(time() . 'salt value');
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $instance = $_POST['instance'];
} else {
    $instance = md5(time() . 'some other salt value');
}
?>
<p>You are session <?php echo $_SESSION['token']; ?>, instance <?php echo $instance; ?></p>
<form method="POST" action="">
    <button type="submit" name="instance" value="<?php echo $instance; ?>">Submit</button>
</form>

One other thing you could do is use encryption or one-way hashing in order to mask, say, a username. So you would pass an encrypted username as your "instance" field, and then decrypt it on the back end (using the session token and instance) to figure out which user is sending a message to the server.

Basically, though, this abuses the concept of PHP sessions. A PHP session is for a browser, not a browser tab/window.



来源:https://stackoverflow.com/questions/28437412/prevent-multi-submit-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!