首页 > 解决方案 > 如何防止页面一起运行或在 PHP 中组合

问题描述

我有两个页面,都是用 PHP 编写的,但是在查看页面时,服务器将这两个页面组合在一起并将它们作为一个页面提供服务。我怎样才能防止这种情况,并收到两个单独的页面?SuperGlobals 在我的环境中受到限制,并且没有 javascript。

  1. 第一页 (index.php)

这是该站点的索引页面。我想要求用户在查看此页面之前正确输入验证码。


<?php
require_once __DIR__ . '/captcha.php';

?>
<!doctype html>
<html lang="en">
    <head>
    <title>You Win!</title>
    <meta charset="utf-8" />
    </head>
    <body>
    <h1>You Really Win!</h1>
    <h2>Win Baby, Win!</h2>
    </body>
</html>
  1. 第二页 (captcha.php)

这是验证码所在的页面,也是我希望在索引页面之前首先出现的页面。

<?php

//To save time and space, This page is highly abbreviated from the actual php file.

require_once __DIR__ . '/vendor/autoload.php';
use Gregwar\Captcha\PhraseBuilder;
use Gregwar\Captcha\CaptchaBuilder;

$captcha = new CaptchaBuilder;
$captcha->build();
$phrase = $captcha->getPhrase();
$phrase = $_SESSION['phrase'];

$check_phrase = PhraseBuilder::comparePhrases($_SESSION['phrase'], $_POST['phrase']);
if (isset($_SESSION['phrase']) && $check_phrase === true)
{
  header('Location: ' . __DIR__ . '/index.php');
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
<form method="post">
    <div>
        Copy the CAPTCHA:
    </div>
    <div>
        <img src="<?php echo $captcha->inline(); ?>" alt="Captcha"/>
    </div>
    <br>
    <div>
        <label>
            <input type="text" name="phrase" />
        </label>
        <input type="submit" />
    </div>
    <br>
    <div>
        &nbsp;
    </div>
</form>
</html>

那么如何将页面彼此分开并使服务器将它们作为两个单独的页面提供服务呢?

标签: phpcaptcha

解决方案


@Barmar 提出的建议是一个开始,但并没有让我成为大本营。通过使用管理两个文件之间的重定向的第三个文件解决了该问题。整个过程在下面提供的图表中进行了解释。

处理流程图

  1. 索引.php

require_once为了使用条件来管理重定向,仍然有助于在此文件上使用。唯一改变的是所需的文件,它是重定向管理器文件start.php

require_once (start.php)
  1. 开始.php

该文件是该问题的新增内容和发现的解决方案。它使用条件来测试用户应该被转发到哪个页面。

if (strcmp($user_secret, $server_secret)
{
  header('Location: index.php')
}
else //inferred not actual
{
 header('Location: captcha.php')
}
  1. 验证码.php

文件中也几乎没有变化,只是便于使用require_once其中的条件句来将使用引导到索引页面。

<?php
require_once __DIR__ . '/vendor/autoload.php';
use Gregwar\Captcha\PhraseBuilder;
use Gregwar\Captcha\CaptchaBuilder;

$captcha = new CaptchaBuilder;
$captcha->build();
$phrase = $captcha->getPhrase();
$phrase = $_SESSION['phrase'];

$check_phrase = PhraseBuilder::comparePhrases($_SESSION['phrase'], $_POST['phrase']);
if (isset($_SESSION['phrase']) && $check_phrase === true)
{
  require_once 'start.php';
}

?>
<form method="post">
    <div>
        Copy the CAPTCHA:
    </div>
    <div>
        <img src="<?php echo $captcha->inline(); ?>" alt="Captcha"/>
    </div>
    <br>
    <div>
        <label>
            <input type="text" name="phrase" />
        </label>
        <input type="submit" />
    </div>
    <br>
    <div>
        &nbsp;
    </div>
</form>
</html>
<?php
}
?>

而且,它完全按照我的预期工作。代码更简单,更直接,过程也更少混乱。


推荐阅读