[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
Related
I'm trying to make a simple captcha in PHP, but it does not work. The query is not currently executing. This is my current code:
<?php
$Random = rand(1, 100);
$Random2 = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
<input type="text" name="r_input"/><br />
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $Random+$Random2;
if(isset($_POST['myButton']) and trim($Var) and trim($Var2) and trim($Var3) and $Cap==$Result){
//My Query
}
When you use rand() to generate 2 values, and show those 2 values, and give the form for the user to enter the answer, ...
... the user enters the answer and submits back to the server ...
... the server gets the answer, and then GENERATES 2 NEW VALUES, that don't correspond to the answer given by the user.
Try using session variables to store the generated values in, and match against when the user submits the form!
<?php
session_start();
$captcha_id = 'captcha_' . rand();
$_SESSION['$captcha_id']['val1'] = rand(1,1000);
$_SESSION['$captcha_id']['val2'] = rand(1,1000);
echo "
<form action='' method='post'>
<p>Result: {$_SESSION['$captcha_id']['val1']} + {$_SESSION['$captcha_id']['val2']} = </p>
<input type='hidden' name='captcha_id' value='{$captcha_id}' />
<input type='text' name='captcha_answer' />
<p>?</p>
</form>
";
if (
isset($_POST['captcha_id'])
&& isset($_SESSION[$_POST['captcha_id']])
&& isset($_POST['captcha_answer'])
&& $_SESSION[$_POST['captcha_id']]['val1'] + $_SESSION[$_POST['captcha_id']]['val2'] == intval($_POST['captcha_answer'])
) {
unset($_SESSION[$_POST['captcha_id']]); // don't let this answer be reused anymore.
// do allowed stuff
}
?>
Because $Random and $Random2 have a different value each time.
When you show the form for the first time, they may have the values $Random = 12 and $Random2 = 26. The User sees those, adds them up correctly and types in 38 (which is the correct answer for those two values). The answer is sent to the script again, the values of $Random and $Random2 are generated again (this time as $Random = 23 and $Random2 = 30 which equals 53) and the answer the user has sent is not correct any more.
So you would need to store those values in hidden fields and add these up, instead of the generated ones, like so:
<input type="hidden" name="rand_1" value="<?php echo $Random; ?>">
<input type="hidden" name="rand_2" value="<?php echo $Random2; ?>">
<?php
if ($_POST['rand_1'] + $_POST['rand_2'] == $_POST['r_input']) {
// Query etc.
EDIT: As suggested by #nl-x you should use the Session variables instead of hidden fields to prevent abuse of the captcha:
<?php
$Random = $_SESSION['rand_1'] = rand(1, 100);
$Random2 = $_SESSION['rand_2'] = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
And check those values against the given result afterwards:
<?php
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $_SESSION['rand_1'] + $_SESSION['rand_2'];
if ($Result == $Cap) {
// ...
You never re-enter PHP mode after you output your form field:
<input type="text" name="r_input"/><br />
<?php // <----this is missing
$Cap = mysql_real_escape_string($_POST['r_input']);
Pardon me, but you are not making a real captcha. The purpose of the captcha is to distinguish the human from the bots. I would highly suggest you to pick a image database, and randomize a function to call a image. Internally, i would check if the text/description of the image matches with what the user typed.
The only thing you will rand() is what image to load from your image database.
That's a not-healthy way to do it, and there are plenty of better ways to do this. But it's more closer to a captcha than just your current code.
There is also a lot of libraries and engines that can do the job for you.
I'm not a pro at PHP, or even programming at all, but i think you're going to the wrong side - your code won't block any... malicious actions at all, or whatever kind of action that you will try to prevent with the captcha.
Search google for the libraries. PhpCaptcha is one of them. And here is a very simple quickstart guide for phpcaptcha.
Here's a code example, extracted from PHPCaptch that I linked above.
At the desired position in your form, add the following code to display the CAPTCHA image:
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
Next, add the following HTML code to create a text input box:
<input type="text" name="captcha_code" size="10" maxlength="6" />
[ Different Image ]
On the very first line of the form processor, add the following code:
<?php session_start(); ?>
The following php code should be integrated into the script that processes your form and should be placed where error checking is done. It is recommended to place it after any error checking and only attempt to validate the captha code if no other form errors occured. It should also be within tags.
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
This includes the file that contains the Securimage source code and creates a new Securimage object that is responsible for creating, managing and validating captcha codes.
Next we will check to see if the code typed by the user was entered correctly.
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
Following the directions above should get Securimage working with minimal effort.
This code is included here as well.
Good luck!
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']) {
Hi I am a newbie learning PHP ( & on stackoverflow too)- I am trying to solve a simple problem but unable to do. I hae already searched on google and stackoverflow before posting a question as I didnt want to waste other time but for a week now am unable to solve this issue.
I am writing a simple program in php that lets user input a number and checks if the value entered is 5. If true it echo's "you win" else "try again". I am able to do this
The tricky part for me is I want to give him only 10 chances and try as I might using basic PHP am unable to do this. Have tried using if, for, do while but am unable to "loop the html"..I dont know jquery etc and am trying to accomplish this with PHP only. I havent yet progessed to learning sessions etc. Thanks in advance
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="hidden" name="cnt" value=<?php $cnt=0 ?>>
<input type="submit" name="go">
</body>
</html>
<?php
$i=0;
if ($_POST['num']!=5)
{
$i++;
echo $i;
echo " Please try again";
}
else
echo "You win the game";
?>'
You need to store the variable in some manner such that it persists. in your script, you are setting $i to 0 each time it runs. Plus you are setting the value incorrectly in your hidden input.
One way of doing this is using a Session variable, such as $_SESSION['cnt']
My PHP is a bit rusty, but here's an example using Session variables:
$max_guesses = 10;
if( !isset($_SESSION['cnt']) ){
$_SESSION['cnt'] = 0;
}
if( $_SESSION['cnt']++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
If you don't want to, or can't use a session variable, you could use the hidden input field, like you tried to:
<?php
if( !isset($_POST['cnt']) ){
$cnt = 0;
} else {
$cnt = $_POST['cnt'];
}
if( $cnt++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
?>
<input type='hidden' name='cnt' value='<?php echo $cnt ?>' />
(Note if your form uses GET instead, just replace $_POST with $_GET or you can use $_REQUEST if you're not sure, but probably better not to.
After successful login of the user set the chances variable to 10 like this.
$_SESSION['nofchances']=10;
After setting this flag on the successful authentication page. Redirect to your PLAIN html code.
EDITED :
question.html
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="submit" name="go">
</body>
</html>
gullible.php
<?php
if($_SESSION['nofchances']!=0)
{
if ($_POST['num']!=5)
{
$_SESSION['nofchances'] = $_SESSION['nofchances'] - 1;
echo "You have ".$_SESSION['nofchances']." no of chances to try";
echo "<br>Please try again";
header("location:question.html");
}
else
{
echo "You won the game";
$_SESSION['nofchances']=10; // resetting back
}
}
else
{
echo "Your chances expired";
}
?>
You can call a function in onBlur/onChange
<script>
function test()
{
var count=<?php echo $count;?>;
var guess=parseInt($('#hid_num').val())+1;
if(guess>count)
{
alert('Your chances over!');
}
else
{
$('#hid_num').val(guess);
}
}
</script>
<input type="text" onblur="test();" id="chk_estimate" />
<input type="hidden" value="0" id="hid_num" /></body>
If you dont want to use sessions yet you could define a hidden input field which stores the current try then incriment "+1" it whenever the submit is pressed / the site is reloaded. Something like:
if( isset($_POST['try']) ) {
$try = $_POST['try'];
$try += 1;
} else {
$try = 0;
}
add the hidden field in your form like:
$hiddenTry = '<input type="hidden" value="'. $try .'" name="try"/>';
and add a if clause to when to show the form like:
if ( $try <= 10 ) {
//your form
}
i made this for you i hope it can help you learn something new (i edited it a couple of times to make variable names easier to understand make sure you check it again - i added a cheat also :) )
<?php
session_start(); // with this we can use the array $_SESSION to store values across page views of a user.
mt_srand(time()); // this is to ensure mt_rand function will produce random values. just ignore it for now. it's another story :)
$max_tries = 10; // limit of guesses
$_SESSION['the_magic_number']=!isset($_SESSION['the_magic_number'])?mt_rand(0,100):$_SESSION['the_magic_number'];
// the previous line is a one-liner if then else statement. one-liners works like this:
// $my_name_will_be=($isBoy==true)?"George":"Mary";
if(isset($_POST['num'])) // if this pageview is from a valid POST then...
{
$_SESSION['current_try']=isset($_SESSION['current_try'])?$_SESSION['current_try']+1:1;
// one-line if then else again. This increases the try user is now, or resets it to one
}
?>
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<?php
if ($_SESSION['current_try']<=$max_tries) // if user has more tries available
{
if(intval($_POST['num'])==$_SESSION['the_magic_number']) // did he found it?
{
echo "You found it! Gongratulations! Click <a href=''>here</a> to try again!";
// oh and do not forget to reset the variables (you found this bug, well done!)
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
else
{
// if he didn't found it, display the status of tries left, and the form to try again
echo "This is your try ".($_SESSION['current_try'])." of ".$max_tries." Good Luck!";
?>
<form method="POST" action="mygame.php">
Please enter any number :
<input type="text" name="num"/>
<input type="hidden" name="tries" value="<?php echo (isset($_POST['tries']))?$_POST['tries']-1:$max_tries; ?>"/>
<input type="submit" name="go"/>
</form>
<span style="color:white;background-color:white;"><?php echo "You bloody cheater! The magic number is ".$_SESSION['the_magic_number'];?></span>
<?php
}
}
else
{
// here we are if no tries left! An empty href to reload the page, and we resetting our variables.
// the_magic_number gets NULL so at the start of script it will be "not set" and will get a mt_rand(0,100) value again
echo "You lost! Sorry! Click <a href=''>here</a> to try again!";
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
?>
</body>
</html>
the span at the end is a cheat ;) press ctrl+a to use it !!!
Trying to get it to loop through 3 times and after the 3rd time (if not guessed right) show the right answer.
Currently - its going through the guesses, but isnt showing how many guesses are left (should be deducting each # each attempt).
Anyone? If you could show me where I'm going wrong here.
<style type="text/css">
input {border:1px solid #ADD8E6; font-size:1.2em;}
input.spec {background-color:#ddd;}
</style>
<?php
echo "<fieldset><h1><legend>Testing your Academy Award Trivia</h1>";
$ages['Casablanca'] = "1943";
$ages['Around The World in 80 Days'] = "1956";
$ages['Patton'] = "1970";
$ages['Annie Hall'] = "1977";
$ages['Chariots of Fire'] = "1981";
$ages['Dances With Wolves'] = "1990";
$ages['Crash'] = "2005";
$ages['The Departed'] = "2006";
$rand_keys = array_rand($ages, 1);
$guesses = 3;
?>
<form method='post' name="inputyear" onsubmit="return validate(this);">
Give the year below won academy award<br><br>
<Strong>Movie:</strong> <input type='text' name='movie' class="spec" value='<?= $rand_keys ?>' readonly='readonly' /><br><br>
<Strong>Year it Won the Oscar:</Strong> <input type='text' name='year' size="30" /><br/><br>
<strong>You have: </strong> <?php $guesses; ?> guesses left<br><br>
<input type='submit' name='submit' value="Get Result" onClick="makeGuess()" />
</form>
<?php
$movie = isset($_POST['movie']) ? $_POST['movie'] : false;
$guessedYear = isset($_POST['year']) ? (int) $_POST['year'] : false;
if ($movie && $guessedYear) {
$realyear = $ages[$movie];
}
#$_SESSION[$movie]['$guesses']++;
if ($realyear && $_SESSION[$movie]['$guesses'] < 3) {
if ($guessedYear == $realyear) {
echo "Correct! " . "during year " . $realyear;
}
if ($guessedYear < $realyear) {
echo "Wrong, year too low";
$guesses--;
}
if ($guessedYear > $realyear) {
echo "Wrong, year too high";
$guesses--;
}
} elseif ($_SESSION[$movie]['$guesses'] >= 3) {
echo "Sorry, too many tries. the answer was " . $realyear;
} else {
echo "Sorry, You managed not to pick a year. Please try again";
$_SESSION[$movie]['guesscount']--;
}
?>
the return statement is leaving the loop and the script
get rid of both return statements
DC
Further to your comments on the duplicate question at...
Allowing 3 attempts at game - php
It would appear that this question is a 'homework' question as such and in fact with all questions no-one will give you the complete answer, nor in my opinion should they. We all expect that the person asking the question will take it upon themselves to investigate and understand the answers given.
Now in the case of your question, you appear to be missing a vital piece of information about how HTTP works (http is the protocol that drives all web pages and many other parts of the internet).
http is what's considered a stateless protocol, that is when you click on a link in a web page and go to another web page (or even the same web page), the new web page considers you a totally new visitor. It in effect has forgotten you.
Because this introduced issues for things like shopping carts (and PHP games) cookies were invented. this allowed the browser to carry around a small bit of information about you, in this way the web server or application remembered you. This has been extended into what respondents here are calling sessions.
A session is (usually) a cookie that stores an identifier. that identifier tells, in this case PHP, that you have been there before and where to find the information about you. PHP can load this information and make it available to you the programmer.
This happens EVERY TIME a page is loaded.
Now PHP does not know what to store in this 'session' it is up to you the programmer to decide what information needs to be stored. you need to tell PHP to save this information for the next time the page is loaded.
In your case its up to you to decide what needs to be remembered. Consider the reloading of the page to be a new 'iteration' of the loop. this should lead you to some obvious conclusions about what needs to be passed from one iteration to the next.
There you go. I haven't written the answer for you but hopefully have provided enough for you to pass your class in flying colours.
DC
I think you're problem is this line $rand_keys = array_rand($ages, 1);. Each time the user submits their answer a new $rand_keys is selected and fed into the dropdown regardless of what the submitted answer was.
So you'll want to check if there exists an answer (otherwise it's the first time the page is loaded). If there is an answer and it was correct then show a congrats message and generate a new movie id.
if($_POST['submit']) {
$movie = $_POST['movie'];
$guessedYear = $_POST['year'];
if ($guessedYear == $ages[$movie]) {
// well done you got it right, next movie
$rand_keys = array_rand($ages, 1);
}
else if ($guessedYear == $ages[$movie] && $_POST['tries'] >= 3) {
// took over 3 tries and didn't get it right, next movie
$rand_keys = array_rand($ages, 1);
}
else {
// find $movie index from $ages and use that
}
// you have one less try
$tries = $_POST['tries'] - 1;
}
else {
$rand_keys = array_rand($ages, 1);
$tries = 3;
}
Then in the form send the $tries variable along with the other ones, or as the other people here have said put it in the session variables. With that I think you should be able to remove the while loop completely.
After you fix what DeveloperChris says, you still need to put guesscount into as session or form field, and increment on each attempt.
if($guesscount < 3 && $guessedYear > $realyear){
echo "Wrong, year too high";
}
if($guesscount < 3 && $guessedYear > $realyear){
echo "Wrong, year too high";
}
duplicate code there. also i think you are looking for if{...}else if{..}else if{...}else{...}
and your question has nothing to do with javascript.
maybe core logic more like this?
$movie = isset($_POST['movie']) ? $_POST['movie'] : false;
$guessedYear = isset($_POST['year']) ? (int) $_POST['year'] : false;
if ($movie && $guessedYear) {
$realyear = $ages[$movie];
}
#$_SESSION[$movie]['guesscount']++;
if ($realyear && $_SESSION[$movie]['guesscount'] < 3) {
if ($guessedYear == $realyear) {
echo "Correct! " . "during year " . $realyear;
}
if ($guessedYear < $realyear) {
echo "Wrong, year too low";
}
if ($guessedYear > $realyear) {
echo "Wrong, year too high";
}
} elseif ($_SESSION[$movie]['guesscount'] >= 3) {
echo "Sorry, too many tries. the answer was " . $realyear;
} else {
echo "Sorry, You managed not to pick a year. Please try again";
$_SESSION[$movie]['guesscount']--;
}
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"];