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"];
Related
Status:
Apprentice.
My PHP knowledge:
Beginner level.
What I am trying to achieve with my PHP code:
Update the health bar input when ever the user clicks on the submit button.
<form>
<input type="submit" value="Attack">
</form>
So if the condition is true and the post has been done then I want to subtract 25 from the variable health which is then equal to another variable named input.
The problem:
I cant figure out why the health is not updating and how to save the updated value even if the user refreshes and then substracting 25 with the updated health everytime the user clicks on "attack".
What I tried:
Apart from doing some PHP research about Session_start() im not sure how to use it in this context. Im not even entirely sure why my conditional is faulty. I get no error messages what so ever but when I remove my if statement and echo the my bar variable then it doesnt work either as I dont get any number at all, which of course makes me suspect that my math is not working.
<?php
$health = 100;
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
if (isset($_POST['submit'])) {
$health - 25 == $input;
echo $bar;
}
?>
Question:
Why does'nt my value of health / input update? How can I save the session and substract from the new variable the next time an attack is made?
Your PHP is stateless so it has no record of what health was - it's simply reset to 100 every time.
You need to either use sessions, or simply pass back in the value of health each time:
<?php
$health = (isset($_REQUEST['health']) ? (int) $_REQUEST['health'] : 100);
if (isset($_REQUEST['submit'])) {
$health = $health - 25;
}
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
?>
<form action="attack.php" method="post">
<input type="submit" name="submit" value="Attack">
<input type="hidden" name="health" value="<?php echo $health; ?>">
</form>
A couple of other points:
1) I'm not sure what the significance of $input is
2) You should really include a method in your form tag of either get or post - in the PHP I've used I have referenced $_REQUEST which features the values of both $_GET and $_POST
3) Notice I cast the value of $_REQUEST['health'] to an integer because this is output in the hidden HTML field and this helps to avoid XSS exploits.
If you want the health variable to carry over on to other pages or scripts then you might prefer to use a session. Revised code as follows:
<?php
session_start();
$health = (isset($_SESSION['health']) ? $_SESSION['health'] : 100);
if (isset($_REQUEST['submit'])) {
$health = $health - 25;
$_SESSION['health'] = $health;
}
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
?>
<form action="attack.php" method="post">
<input type="submit" name="submit" value="Attack">
</form>
One final comment is that using the session method a user cannot tamper with their own health score. Whereas using the hidden input method the user could potentially change the value of the field and tamper with their health score if they had the technical know-how.
change the form to the form below -
<form action='' method='POST'>
<input type="submit" name='submit1' value="Attack">
</form>
Then you can do -
if (isset($_POST['submit1']))
{
echo "button was pressed";
/// do other stuff.....
}
Define your form like:
<form method="POST">
That might do the trick. And you might need an hidden input field for the current health.
Firstly, forms default to a GET method if omitted.
Therefore, you need to specify it in your form tag
method="post"
Then your conditional statement will fail, since the submit input doesn't have the name attribute.
Add name="submit" to it.
Then this $health - 25 == $input; that doesn't make any sense and I don't know what you're trying to do here.
As stated in another answer by Mr Carrot, you'd want to use $health = $health - 25;
I'll let you look through the answers given, but this gives you a good indication as to what's going on.
Using error reporting would have signaled notices.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
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']) {
I'm working on a little project, basically I have some text on my PHP/HTML page that is being echo'ed from a variable ($brief_string).
There is also a back, and continue button which basically subtracts or adds to another variable ($brief_page - which is pulled from my DB). The brief_string changes depending on the brief_page by using if statements. First problem I encounter is that when I hit continue (submit button) it resubmits/refreshes the page, causing my brief_page to reset back to 0.
So I'm thinking maybe I could use JS to hold the info and page variables and control the dynamic text, but then, how would I update my DB with the current page value via JS? Isn't it really easy to manually change/hack these values? I would preferably like my DB to be updated with the page number each time the use presses the back/continue button.
I would just like some advice really as I am a student trying to develop an interactive book like site (that uses a DB to save your current page).
Code:
<?
$brief_info = "brief info goes here";
$brief_page = 0; //< will soon be pulled off DB
if (isset($_GET['brief1Go'])) {
$brief_page = $brief_page + 1;
}
else if (isset($_GET['brief1Back'])) {
$brief_page = $brief_page - 1;
}
$breifController = "
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Back\" id=\"brief1Back\" value=\"BACK\" />
</form>
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Go\" id=\"brief1Go\" value=\"CONTINUE\" />
</form>";
if($brief_page == 0){
$brief1_info = "<b>Welcome Commander,</b> you are currently viewing the Mission Control Brief page, here you can view all your missions that you need to complete in order to advance through your prestiges. You will need to follow your briefs carefully in order to succeed. <br /><br />
";
}
else if($brief_page == 1){
$brief_info = "Okay, let me show you around the place ...";
}
else if($brief_page == 2){
$brief_info = "brief is on 2";
}
?>
Why not just use get vars entirely?
yes, start at 0 unless $_GET['page'] is set...
$brief_page = 0;
if(isset($_GET['page']))
$brief_page = $_GET['page'];
then only use links to your next and previous pages instead of some weird post thing.
Previous Next
where obviously the page numbers in the previous and next are just echoed from php
$prev = $brief_page - 1;
$next = $brief_page + 1;
The user specific things to store can easily be handled with sesisons, cookies or even other get vars if you want to introduce a horrible security hole. Your choice really.
I would definitely not do this via $_POST though. totally annoying. Go with all full on ajax if you want to do that. At least you won't pester the user with "are you sure you want to resubmit the form data" messages if they choose to refresh the page.
[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