Search code examples
phphtmlformsvariablescall

Undefined value when calling an input from a HTML form from PHP


Getting some issues with my PHP. I'm trying to get assign the value from the text box to a variable so that I can check it against a random number.

This is me initializing my variables:

session_start();
if (!isset ($_SESSION["rand"])) {
$_SESSION["rand"] = rand(0,100);}
$rand = $_SESSION["rand"];

if(!isset ($_SESSION["att"])) {
$_SESSION["att"] = 0;}

This is the form itself:

<form method="post">
<input type="text" id="guess" name="guess"/>
<input type="submit" value="Guess"/>
</form>

and this is the part that is causing the problem:

$answer = htmlspecialchars(trim($_POST["guess"]));

This is the error I'm receiving enter image description here

I'm trying to achieve it to say nothing really, I know that it's because guess hasn't had anything defined to it but I'm not really sure what to define it while I don't need it.


Solution

  • Since you're using everything in one file <form method="post"> is what gave it away, since the action defaults to "self" if omitted, therefore you need to use a conditional isset() or !empty().

    • Consult my "footnotes" also.

    I.e.:

    if(isset($_POST["guess"])){
    
       $answer = htmlspecialchars(trim($_POST["guess"]));
    
    }
    

    or

    if(!empty($_POST["guess"])){
    
       $answer = htmlspecialchars(trim($_POST["guess"]));
    
    }
    

    References:


    Footnotes:

    Even if you were to split those up into two seperate files, it would be best to still use a conditional isset() or !empty().