0

I have done a simple form like this:

index.php:

<!DOCTYPE HTML>
<html>
  <head></head>
  <body>
<?php
  $name = "";
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
      // handle missing field
    } else {
      $name = $_POST["name"];
    }
  }
  if($name != '') {
    header('location: http://localhost/new_page.php');
    exit();
  }
?>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
      <span class="label">Name</span>
      <input type="text" name="name">
      <button><span>Validate</span></button>
    </form>
  </body>
</html>

I would like the following behaviour:

  • staying on the form if the name field is not set by the user
  • going to new_page.php if name field is set

I have the following error right now: if I set the name, I am redirected to a blank.php page. Can someone help me on this ? Or at least give me some tips to debug this as I am not really a PHP specialist.

Thank you !

klaus
  • 754
  • 8
  • 28

2 Answers2

2

Your header call comes too late.

an HTTP Response first has a header, then a body. HTML code is the body.

You need to put all output AFTER your PHP code. Since you start with <html>, headers will already have been sent and so your redirect will not work.

Also, regarding white pages (White screen of death or WSOD):

For the best error logging experience, set error_reporting to -1, turn display_errors off, and set a custom error_log. Then in the terminal, type 'tail -f /path/to/error_log'. Your notices, warnings and errors will now scroll past in real time, without distorting your web page's display.

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
0

The answer given by @delboy1978uk is correct. All you have to do is change your file content to:

<?php
  $name = "";
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
      // handle missing field
    } else {
      $name = $_POST["name"];
    }
    if($name != '') {
      header('location: http://localhost/new_page.php');
      exit();
    }
  }

?><!DOCTYPE HTML>
<html>
  <head></head>
  <body>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
      <span class="label">Name</span>
      <input type="text" name="name">
      <button><span>Validate</span></button>
    </form>
  </body>
</html>
CarlosCarucce
  • 3,420
  • 1
  • 28
  • 51