Can't retrieve data from session variable - PHP Number guessing game - php

I am building a number guessing game and need to create a session variable to hold the randomized target number until the user submits the correct guess. I also need to print the number of attempts after the user submits the correct answer.
I set my session variable and used a hidden field to hold the counter. I don't know if the hidden field works bc when I submit a guess, my code prints out the first if statement of the check() function..ALL THE TIME.
I think it has something to do with the session variable (and of course my code), but I can't figure it out. I've been working on this for two days now and feeling the frustrations. Any help would be amazing. Here's my full code below:
<?php session_start() ?>
<!DOCTYPE HTML>
<html>
<head>
<title>Number Guessing Game</title>
</head>
<body>
<h1>Guess the number</h1>
<p>I'm thinking of a number between 1 and 5. Can you guess what it is?<br>
In less than 3 tries?</p>
<?php
extract($_REQUEST);
error_reporting(E_ALL & ~E_NOTICE);
// check to see if this is start of game
if (filter_has_var(INPUT_POST, "guess")) {
check();
} else {
setTarget();
} //end if
// set targetNum session variable
// increment counter by 1
function setTarget() {
$targetNum = rand(1, 5);
$_SESSION["targetNum"] = $targetNum;
$counter++;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
}
function check() {
global $counter;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess"
value= "$guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
if ($guess == $_SESSION['$targetNum']) {
print "<h3>Awesome. You guessed it in $counter attempt(s)</h3>";
unset($_SESSION["targetNum"]);
$count = 0;
print "<a href='numberGuessingGame.php'>TRY AGAIN</a>";
} else if ($guess > $_SESSION['$targetNum']) {
print "<h3>Too high. Guess again.</h3>";
} else if ($guess < $_SESSION['$targetNum']) {
print "<h3>Too low. Guess again.</h3>";
} else {
print "I don't know what that is...";
}
}
?>
</body>
</html>

You made two basic, but severe errors.
First: DO not set the error level to exclude notices when developing! That way you will never spot typos in variable or array index names. Remove error_reporting(E_ALL & ~E_NOTICE);, or replace it with error_reporting(E_ALL);.
Second: You use extract($_REQUEST); - using that function is asking for trouble. PHP has a long history of security vulnerabilities because of the "register_globals" feature, which introduces global variables just because some key=value pair in the request data was parsed. It took years to remove that feature. You are re-implementing it without any security precaution by using that function, and with no real benefit.
Remove that extract($_REQUEST); function, and use $_REQUEST['varname'] instead of $varname for all variables that come from the remote browser.

Your $guess variable is never set to the POST value (Correction: you're using extract but I'd advise against it). You are also changing the value of your session array key when you add a '$':
$guess = $_POST['guess'];
if ($guess == $_SESSION['targetNum']) {

Related

In PHP, how to keep a random number var from changing each time input is changed?

I am attempting to make a random number guessing game in PHP. The guesses are entered into the $_GET var in the address bar after a ?. However, each time the enter key is pressed the random number itself changes. How can I keep this random number intact until the game is lost or won.
<!DOCTYPE html>
<html>
<head>
<title>Guess Gaming</title>
</head>
<body>
<h1>Guess the correct Number</h1>
<p>
<?php
$randomNum = rand(0, 150);
if(empty($_GET["guess"])){
echo "Missing guess parameter.";
} elseif(!empty($_GET["guess"])){
if(is_numeric($_GET["guess"])){
if($_GET["guess"] === $randomNum){
echo "Congratulations-- You are right";
} elseif($_GET["guess"] < $randomNum){
echo "Your guess is too low.";
} elseif($_GET["guess"] > $randomNum){
echo "Your guess is too high.";
}
} else {
echo $_GET["guess"]." isn't numeric.";
}
}
?>
</p>
<p>
<?php
echo $randomNum;
?>
</p>
</body>
</html>
Use sessions. Put session_start(); at the top of your PHP script.
Generate a new random number whenever the current one is guessed, or if there is none yet:
if (!isset($_SESSION['secret_random_number']))
{
$_SESSION['secret_random_number'] = mt_rand(0,150);
}
Get the previously stored number like this:
$randomNumber = $_SESSION['secret_random_number'];
Store the correct answer in a session variable. Session variable persist from page to page and aren't visible to the end user.
http://php.net/manual/en/session.examples.basic.php
EDIT:
Adding the code example from the documentation, since some people are otherwise voting in retaliation to delete a completely valid answer simply because it doesn't have code.
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
That is the code principle. Just change out the variable names and use your existing logic for generating the random number.

Constant Variables in PHP after page reloads

im very new to PHP, so please excuse me if this is a stupid question.
So here is the scenario.
Im writing a PHP all in one page that gets a random word from an array, scrambles the word, then lets the user guess the word.
now im using the isset(), so it declares the variable, then once submit is clicked, it will get in user input via _POST().
Now the problem
I need the calculated variable to remain constant, but once the page reloads, it regenerates the variable.
is there anyway i can get pass this?
<?php
function GetShuffWord()
{
$arrayName = array('word1','word2','word3','word4','word5');
$randWordIndex = rand(0,4);
$randomWord = $arrayName[$randWordIndex];
$shuffledWord = str_shuffle($randomWord);
return $shuffledWord;
}
if(!isset($_POST['Submit']))
{
define("shuffledWord", GetShuffWord());
$tempWord = shuffledWord;
// showing the user shuffled word
echo " <h1 style='font-size: 50px' align = 'center'> {$tempWord}
</h1>";
}
else
{
$tempWord = shuffledWord;
echo " <h1 style='font-size: 50px' align = 'center'>{$tempWord} </h1>";
echo "else part";
}
?>
another problem is that if i declare the variable in the if, i cannot use variable in the else with out re-generating it.
You can just include the value as a hidden input field in your form.
<input type="hidden" name="myCalculatedValue" value="<?= $tempWord ?>" />
Then when the form is submitted you can just get it via $_POST['myCalculatedValue']
You can use session and put a check that if session has it already dont overwrite.
And when u want to overwrite you can do so as well by passing another flag to the script in your post request.

PHP cookies setting

I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.

PHP can't iterate through too high or too low

[Disclaimer: I am new to PHP, and I am just learning, so please no flamers, it really hinders the learning process when one is trying to learn, thank you.]
The code below runs, the only problem is that it does not tell the user when the number is too high or too low, I am doing something wrong, but I can't see the error?
<?php
//Starts our php document
if (!$number)
//if we have already defined number and started the game, this does not run
{
Echo"Please Choose a Number 1-100 <p>";
//gives the user instructions
$number = rand (1,100) ;
//creates number
}
else {
//this runs if the game is already in progress
if ($Num >$number)
{
Echo "Your number, $Num, is too high. Please try again<p>";
}
//if the number they guessed is bigger than number, lets user know, guess was high
elseif ($Num == $number)
{
Echo "Congratulations you have won!<p>";
//if the number they guessed was correct it lets them know they won
Echo "To play again, please Choose a Number 1-100 <p>";
$number = rand (1,100) ;
//it then starts the game again by choosing a new value for $number that they can guess
}
else
{
Echo "Your number, $Num, is too low. Please try again<p>";
}
//if the answer is neither correct or to high, it tells them it is too low
}
?>
<form action = "<?php Echo $_SERVER[’PHP_SELF’]; ?>" method = "post"> <p>
<!--this sends the form back to the same page we are on-->
Your Guess:<input name="Num" />
<input type = "submit" name = "Guess"/> <p>
<!--Allows the user to input their guess-->
<input type = "hidden" name = "number" value=<?php Echo $number ?>>
<!--keeps passing along the number value to keep it consistent till it is guessed-->
</form>
</body>
</html>
I am assuming $Num is undefined and I am assuming you are assuming it will be defined be cause it is defined in the form.
Try this at the start of your script:
if(!empty($_POST)) {
$Num = (int) $_POST['Num'];
}
$number is not automatically set to the value the <input> field has. (It was in early versions of PHP). You now have to use $_POST['number'] and $_POST['Num'] for this.
register_globals in your php.ini is probably Off (and that's a good thing) and therefore you can only access those variables through $_POST['Num'] and $_POST['number'] (you can just assign $number=$_POST['number'] at the beggining of your script)
also, sending the secret $number through form is not nice, you might want to read about php sessions
Suggestions:
1) use echo, not Echo
2) do not forget to close the p tag

Struggling with hidden form field basics (PHP)

I'm having difficulty using hidden forms with PHP data. I cannot for the life of me figure out what I'm doing wrong.
My code should
Check to see if an attack succeeded;
If it succeeded, subtract damage from health;
Rewrite the $health variable.
Use the new $health value for the next round.
The problem is, it keeps resetting the health value.
Here is my code (it's set so that the attack always succeeds):
<?php
$health = $_REQUEST["health"];
$attack = rand(10,20);
$defend = rand(1,9);
$damage = rand(1,5);
$health =50;
if ($attack>$defend){
print "<p>Jim hit the robot for $damage.</p>";
$health = $health - $damage;
print "<p>The robot has $health health remaining.</p>";
} else {
print "<p>Jim missed.</p>";
print "<p>The robot has $health health remaining.</p>";
} // end if statement
print <<<HERE
<input type="text"
name="openMonsterHealth"
value="$health">
<input type="hidden"
name="hdnMonsterHealth"
value="$health">
<input type="submit"
value="click to continue">
HERE;
?>
If you want $health to follow you to the next page, use sessions.
PHP Manual on Sessions
Basically, you'd start your pages with
session_start();
if(isset($_SESSION['health'])) {
$health = $_SESSION['health'];
}
else {
//However you normally set health when the user is just starting
}
which would load the health value from the previous page, if you set it like this:
$_SESSION['health'] = $health;
PHP scripts automatically write and close sessions, so you don't have to worry about anything other than creating a variable in the session global array. Just don't forget to start your sessions when you want to retrieve the data in the session array from the previous page. Your users, however, will have to be able to accept cookies.
If you keep using hidden fields, a player could change that information before sending it back to you (plus, they're more trouble to keep track of).
edit:
Your bugs, however, are you're resetting your health to 50 on the 5th line of your code, you're not using the right variable name for health from the request, and you don't have any form tags.
<?php
if(isset($_REQUEST['hdnMonsterHealth']))
$health = $_REQUEST['hdnMonsterHealth'];
else
$health = 50;
$attack = rand(10,20);
$defend = rand(1,9);
$damage = rand(1,5);
if ($attack > $defend) {
print "<p>Jim hit the robot for $damage.</p>";
$health = $health - $damage;
print "<p>The robot has $health health remaining.</p>";
} else {
print "<p>Jim missed.</p>";
print "<p>The robot has $health health remaining.</p>";
} // end if statement
print <<<HERE
<form method="post">
<input type="text"
name="openMonsterHealth"
value="$health">
<input type="hidden"
name="hdnMonsterHealth"
value="$health">
<input type="submit"
value="click to continue">
</form>
HERE;
?>
Edit: Sorry for all of the weirdness, formatting is broken by this block of code, so I had to manually insert every < in the code with <. This code works now, however.
You still have a bug of negative health. I'm not writing your game for you, though.
Sorry, you haven't mentioned what scope your $health variable is. Does it belong to the session, or just for the lifetime of the request?
I'd strongly encourage using session variables, i.e.:
$_SESSION["health"] = $_SESSION["health"] - $_REQUEST["DAMAGE"];

Categories