-1

I am trying to run my PHP code, but I am getting an undefined error for the $name variable. The error will show only when it runs for the first time only, but after the second run, it didn't show any error.

<?php
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $name =  $nameerr = "";
        if(empty($_POST["name"])){
            $nameerr = "This Field is Required";
        }
        else{
            $name = test_run($_POST['name']);
        }
        }


        function test_run($data){
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }
    ?>
    <form action="<?php htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST">
    <label for="name">Name: </label>
    <input type="text" name="name" value="<?php echo $name;?>"><span>* <?php echo $nameerr ?></span><br><br>
    <input type="submit" value="Submit">

    </form>
    <h1>Output</h1>
    <?php
    echo $name."<br><br>";
?>
Rabner Casandara
  • 151
  • 3
  • 18

1 Answers1

-1

This is because you are not setting the $name variable initially. You are only setting it when a post request is made. So the first time you fetch your script with a GET request, PHP shows you the notice. The second time ( I presume is after you submit your form which initiates a POST request ) the $name variable is set, thus, you do not receive the notice. To resolve this, you can set your $name variable to an empty string above your first if statement.