关于在加载HTML文件之前通过php修改HTML文件的内容


About modifying the content of an HTML file through php before loading the HTML file

比如说,如果我运行PHP时密码/用户名不匹配,我想回到我的主登录页面,该页面全部为HTML/JS。我希望能够访问我的主登录html页面,并使包含错误消息的div可见

以下是帮助示例的代码片段。一切都很好,我只是不喜欢我所能做的就是加载索引页面而不告诉我的用户出了什么问题。我一直在谷歌上搜索,但我没能把它做好

<?php //this is in a separate file "checklogin.php"
. 
. 
.
    if ($count == 1) {
            session_start();
            $_SESSION['loggedin'] = true;
            header('Location: loggedin.php');
        }
         else {
            header('Location: index.php');
        }   
.
.
.
?>

<html> //separate file "index.php"
    <body>
    .
    .
    .
       <div id = "nomatch" name = "nomatch" style = "display:none">
         <p>
           username and password don't match
         </p>
       </div>
    .
    .
    .
    </body>
 </html>

您只需在index.php重定向中添加一个参数:

header('Location: index.php?error');

你的index.php变成:

<?php if (isset ($_GET['error'])) { ?>
<div id = "nomatch" name = "nomatch" style = "display:none">
     <p>
       username and password don't match
     </p>
   </div>
<?php } ?>

有大约1000种不同的方法可以做到这一点。这完全取决于你如何处理登录表单。最简单(但不一定是最好的)的方法是返回一条附加在URL上的错误消息。

例如,重定向到http://example.com?error=badpassword,然后在您的代码中,您可以使用检索它

Error: <?php echo 'error:' . $_GET["error"]; ?>.

更多信息请点击此处:http://www.w3schools.com/php/php_get.asp

编辑:基本如下。。。必须是在我键入答案时提交的

index.php替换index.html,并在调用index.php页面时传递URL变量,意思是:

index.php:

<?php if(isset($_GET['errors'])) {
    $errors = $_GET['errors'];
?>
<html>
    // some html tags
    <?php if($errors): ?>
        <div> your div error </div>
    <?php endif; ?>
</html>

并像这样调用该文件:header('Location: index.php?error="what you want"');