1

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.

w3spi
  • 4,380
  • 9
  • 47
  • 80
Tauntaunwampa
  • 61
  • 1
  • 6

2 Answers2

4

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().

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • 1
    Beat me to it. Good job – Drakes May 23 '15 at 13:53
  • That seems to have solved that issue, but now it won't recognise `$answers` outside of the `if` statement. Also, thank you for your time! – Tauntaunwampa May 23 '15 at 14:01
  • I know what I did wrong, no need to reply. Thank you for your help! – Tauntaunwampa May 23 '15 at 14:08
  • @Tauntaunwampa You're welcome. If you wish to check the value against the POST array and the session array, you need to compare both of those inside that conditional statement. There seems to be missing that part. I.e.: `$_POST["guess"] = $_SESSION["rand"];` or `$_SESSION["rand"] = $_POST["guess"];` with a conditional `if` and `==`. – Funk Forty Niner May 23 '15 at 14:10
  • @Tauntaunwampa You're welcome, glad to to know it's been resolved, *cheers*. – Funk Forty Niner May 23 '15 at 14:11
2

Use a conditional isset(). It is used to check if a variable is set or not.

When you initially load the page, your POST data is not set and that is the reason why you got that notice.

if(isset($_POST["guess"]) && $_POST["guess"] !=""){
   $answer = htmlspecialchars(trim($_POST["guess"]));
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Saty
  • 22,443
  • 7
  • 33
  • 51