0

I'm very new to PHP and I've cobbled this together from some other answers on here. Can anyone show me how to get the $errMsg to display? At present, a blank or incorrect name leads to a blank page. Is this because the form isn't being displayed again? If so, how should I go about 'reloading' the form with the error message?

<?php
$name = "Fred";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  if (!empty($_POST["name"])) {

      if ($_POST["name"] == $name) {
        include("welcomeFred.php");
      }

      else {
        $errMsg = "Incorrect name";
      }

  }

  else {
    $errMsg = "Name required";
  }

}
else { ?>

  <html>
  ...
  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <input type="text" name="name" required>
    <span><?php echo $errMsg;?></span>
    <input type="submit" value="Submit">
  </form>
  ...
  </html>

<?php } ?>
3
  • 1
    There is no need to put <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> in the action field of your form. If you leave this blank, the form will be sent to the current url. Commented Feb 13, 2017 at 13:39
  • @Jerodev But are there any security issues with the 'blank' approach? Commented Feb 13, 2017 at 13:50
  • Not that I can see, anyone could change that value using the html inspector, so if you leave it blank or not, the security will be the same. Commented Feb 13, 2017 at 13:51

1 Answer 1

1

You shouldn't put the rendering of the form in the else of your if structure. This is the reason your form isn't loaded when you submit the form.

Remove the else { ?> and <?php } ?> at the end of your file and it should work fine.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you - that makes a lot more sense, it's working now.
Glad I could help. Consider marking this answer as the solution if this helped you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.