Solution 1 :

In your PHP code, you should check whether the request is a POST before trying to handle POST elements:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if ($_POST['username'] === '') {
    echo "<p>Welcome, stranger.</p>";
  } else {
    echo "<p>Welcome, {$_POST['username']}.</p>";
  }
}
?>

This will not run your existing code if the page is not a POST, and therefore the situation causing the error will not occur.

Solution 2 :

I can imagin you’re getting an “Undefined index” error from php. In this case it’s because you’re trying to access a field which does not exist when you’re loading the page with a GET request.

To circumvent this you can check if this key exist.

if (array_key_exists('username', $_POST) && $_POST['username'] === '') {

Problem :

So I have made a small form in HTML, which allows users to enter their name, and then it is displayed on the site. This works fine apart from the first time you visit the page since the input field doesn’t hold a value yet, and so it displays an error message when trying to render the PHP. I was wondering whether there is any way to set a default value for the input field so I don’t get this error.

Here is my code:

<html>
<head>
    <title>My PHP Site</title>
</head>
<body>
    <h1>My PHP Site</h1>
    <form action="dynamictest.php" method="post">
        <input type="text" name="username" placeholder="Username">  
        <input type="submit"><br>
    </form>
    <?php
      if ($_POST['username'] === '') {
          echo "<p>Welcome, stranger.</p>";
      } else {
          echo "<p>Welcome, {$_POST['username']}.</p>";
      }
    ?>
</body>
</html>

Comments

Comment posted by misorude

Research the actual phrasing of the error message you are getting, and you will find plenty of explanations on how to properly handle this.

By