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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Beat me to it. Good job
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!
I know what I did wrong, no need to reply. Thank you for your help!
@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 ==.
@Tauntaunwampa You're welcome, glad to to know it's been resolved, cheers.
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"]));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.