PHP не может установить токен сеанса при отправке формы - PullRequest
0 голосов
/ 25 мая 2018

У меня проблема с моей формой PHP.У меня есть изображение в качестве кнопки отправки в моей форме, и я не могу установить маркер сеанса при отправке формы.При написании кода токен устанавливается при загрузке страницы.Это не сильно беспокоит меня, но мне нужно, чтобы он был установлен или сброшен при отправке формы.Может кто-нибудь сказать мне, что я делаю не так?Вот код:

<?php
// Initiate the session.
session_start();
// Simple function to return a timestamp.
function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
// Generate the token.
function generateToken() {
    // generate a token from a unique value, took from microtime...
    $token = "myFormToken-" . microtime_float();  

    // Write the generated token to the session variable to check it against the hidden field when the form is sent
    $_SESSION['myFormToken'] = $token; 
    return $token;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>This Is My Webpage...</title>
</head>
<body>
<h1>Click on the image below to be taken to the next page..</h1>
<br /><br />
<!-- BEGIN My Form -->
<form action="http://www.mywebsite.com/mypage.php" method="post" target="_top">
<input type="hidden" name="myFormToken" value="<?php echo generateToken(); ?>">
<input type="image" src="http://www.mywebsite.com/myimage.jpg" border="0" name="submit" alt="Click this image!">
</form>
<!-- END My Form -->

</body>
</html>

Спасибо за вашу помощь!

Брайан

Ответы [ 2 ]

0 голосов
/ 24 февраля 2019

Приношу свои извинения за то, что не опубликовал это раньше.Вот решение, которое я в итоге придумал.Обратите внимание, что некоторая информация была удалена для защиты моего кода.Я надеюсь, что то, что я написал здесь, может кому-то помочь.

<?php
// Initiate the session.
session_start();

$myname =""; // Sender Name
$mynameError ="";
$mysoftwarelicensetoken = "";
$mylicensetokenError = "";

// Set this so that we don't go into the function below, until the form posts.
$errors = 1;

// Simple function to replicate PHP 5 behaviour
function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

// Set the token here to prevent any user going to this page and then
//   getting back to the sumbit page.
$_SESSION["myformtoken"] = "myunknowntesttoken";

// Set the variable so that we get into the 'if' section below.
if(isset($_POST['submit'])) { // Checking to see if the form posted.

    $errors = 0;
    //$myname = $_POST["myname"]; // Sender Name
    $mysoftwarelicensetoken = $_POST["mysoftwarelicensetoken"];

    if (!isset($_POST["mysoftwarelicensetoken"])){
        $mylicensetokenError = "You must accept the license agreement";
        $errors = 1;
    } else {
        if ($mysoftwarelicensetoken !== "Yes") {
            $mylicensetokenError = "You must accept the license agreement";
            $errors = 1;
        } else {
            $errors = 0;
        }
    }

    // Set the token again, just for safety's sake.
    $_SESSION["myformtoken"] = "myunknowntesttoken";
}

// This will run when the form posts.
if($errors == 0){
    // Set output SESSION variable. 
    $_SESSION["myformtoken"] = 'myformtoken_intro_' . microtime_float();

    // Re-direct to payment website for payment processing.
    header('Location: https://www.mypaymentwebsite.com');
}
// header("Cache-Control: no cache");
// session_cache_limiter("private_no_expire");
?>
<!DOCTYPE html>
<html>
<head>This Is My Webpage...</head>
<body>
<h1>Click on the image below to be taken to the next page..</h1>
<br /><br />
<!-- BEGIN My Form -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" enctype="multipart/form-data">
<label>Do you accept the <a href="mysoftwarelicense.html" class="underlinelink">license agreement</a>?<br />
    You MUST do so to proceed with your purchase.</label>
<div>
<input type="radio" name="mysoftwarelicensetoken" value="Yes" <?php if (isset($mysoftwarelicensetoken) && $mysoftwarelicensetoken == "Yes") echo "checked"; ?> > Yes
<input type="radio" name="mysoftwarelicensetoken" value="No" <?php if (isset($mysoftwarelicensetoken) && $mysoftwarelicensetoken == "No") echo "checked"; ?> > No
</div>
<div class="error"><?php echo $mylicensetokenError;?></div>
<br />
<input class="submit link-button btn btn-outline-primary btn-lg" type="submit" name="submit" value="Buy It Now" id="myBuyButton">
</form>
<!-- END My Form -->

</body>
</html>
0 голосов
/ 25 мая 2018
<?php
// Initiate the session.
session_start();
// Simple function to return a timestamp.
function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
// Generate the token.
function generateToken() {
    // generate a token from a unique value, took from microtime...
    $token = "myFormToken-" . microtime_float();  

    // Write the generated token to the session variable to check it against the hidden field when the form is sent
      $request = filter_input(INPUT_SERVER, "REQUEST_METHOD");
   if($request === 'POST')
    $_SESSION['myFormToken'] = $token;
   } else{
$_SESSION['myFormToken'] = $token;
}
    return $token;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>This Is My Webpage...</title>
</head>
<body>
<h1>Click on the image below to be taken to the next page..</h1>
<br /><br />
<!-- BEGIN My Form -->
<form action="http://www.mywebsite.com/mypage.php" method="post" target="_top">
<input type="hidden" name="myFormToken" value="<?php echo generateToken(); ?>">
<input type="image" src="http://www.mywebsite.com/myimage.jpg" border="0" name="submit" alt="Click this image!">
</form>
<!-- END My Form -->

</body>
</html>
...