0

I have this page for submitting my answer as a form into another PHP file names processGame.php

<?php
$factor1 = rand(2, 12);
$factor2 = rand(2, 12);
$answer = $factor1 * $factor2;
$score = 0;
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="imageContainer1">
            <?php echo $factor1; ?>
        </div>
        <div id="imageContainer2">
            <?php echo $factor2; ?>
        </div>       

        <div id="form">
            <form method="post" action="processGame.php">
                <textarea type="text" name="userInput" maxlength="3" style="width: 150px; height: 95px; position: absolute; top: 250px; left: 20px; font-size: 80px;"></textarea>
                <input type="hidden" name="answer" value="<?php echo $answer; ?>">
                <input type="submit" name="enter" value="Enter" style="width: 120px; height: 100px; font-size: 40px; position: relative; top: 250px; left: 180px;">
            </form>
        </div>
    </body>
</html>

On submitting I go to this processGame.php which I have the codes like this:

<?php
$input = $_POST['userInput'];
$answer = $_POST['answer'];
$score = 0;
$counter = 0;

for ($counter = 0; $counter <=5; $counter++) {
    if ($input == $answer) {
        $score = $score + 1;
        header("location:game.php");
    } else {
    $score = $score;
}
}
?>

</html>

However the scores can't be consolidated and it does not print out the scores after looping for 5 rounds. Please help me out! :(

greentea
  • 15
  • 1
  • 2
  • `header()` will relocate your whole page. So it won't continue after the first check. `$score` is also limited to processGame.php and its value will never reach your game.php – T3 H40 Jan 13 '16 at 06:49
  • Hi, thanks for the response. Very much appreciated. Other than header() what can i use to consolidate the scores while the page shows a new question? – greentea Jan 13 '16 at 07:12
  • have a look at may answer, I gave a full explanation on whats going wrong and how you should proceed. I also added some links with further information on the topics – T3 H40 Jan 13 '16 at 07:20
  • How did it go? Any success? – T3 H40 Jan 14 '16 at 07:26
  • Nope. I still can't get it. :( – greentea Jan 14 '16 at 08:14
  • What have you tried? What does not work? Have you read into (and understood) the concepts I linked you to? I currently do not have time to write detailed answers, but maybe I can have a look at your code later today. – T3 H40 Jan 14 '16 at 08:16
  • I have tried using function to check the answers using a single php file but everything does not work and I was so annoyed so i deleted the file and left with my old file. D: – greentea Jan 14 '16 at 14:13
  • I added some working code to my answer. Read it, make sure to understand it, and extend it to your needs! This is not intended as complete solution but as starting point! – T3 H40 Jan 14 '16 at 17:15
  • Has it done the job? I hope so :) as you are new to the system, let me introduce you to what to do with your question. On stackoverflow it's common etiquette to vote on and to accept the most helpful answers to your (and other) questions. This way you mark the answer as helpful to you and others, and the answerer gets some reputation that functions as indicator on how much the community trusts in his competence. Read a Minute on why and how to vote or accept [here](http://stackoverflow.com/help/someone-answers) and or comment if you had problems applying the solution :) – T3 H40 Jan 15 '16 at 17:50
  • Thanks for helping! it works! – greentea Jan 16 '16 at 07:28

2 Answers2

0

You are not sending the $score over another page. Send the score while redirecting like this:

header("location:game.php?score=$score");

You can get this score in game.php using $score=$_GET['score'];

Rayon
  • 36,219
  • 4
  • 49
  • 76
  • Hi, thanks for the response. But it still does not work. The score is printed as 000 :( plus it does not loop the number of times i assigned. it keeps going to the page if the answer is correct. – greentea Jan 13 '16 at 06:40
  • @greentea, Question was about retrieving the `$score`. You need to check your logic @ `processGame.php`. Why are you looping it through ? If answer is correct then what should happen ? – Rayon Jan 13 '16 at 06:51
  • I am looping it like 5 times. So that the user will be questioned 5 times. Then I want to consolidate the scores for the 5 times. If the answer is correct, the score will + 1. If the answer is wrong, the score will remain as it is. After the 5 times, the total score will be printed out. – greentea Jan 13 '16 at 07:08
0

What is happening?

There are a few problems with your code. Lets have a quick look at it:

First, here is what your code will do:

  • Create and display an input form (game.php)
  • Redirect to processGame.php on submit and there:
    • Enter a loop
    • check, whether input equals answer
    • if so, increase the local variable $score by 1 and
    • redirect to game.php

So here is what is going wrong:

  • The reason that you do not get any score displayed, is that $score is only accessible within $processGame.php.
  • Once the header() is reached, processGame.php will be left, and no more code will be executed. That is why you will never go further then the first iteration.
  • Your loop will not take any effect. Every time you submit your game.php form, processGame.php will be handled as if it would have never been opened before. So your loop will alway start at 0 (and would also run 6 times by the way! - use <5instead of <=5).
  • You will also see the problem when entering a wrong answer. Your loop will run 6 times and then stop, leaving you with a blank page.

Well, what could you do instead?

There is a lot to work on, as I hopefully explained understandable. I can and will not provide a full code here, because this would basically mean rewrite everything you provided. But I suggest having a read on following topics and rethinking your code:

Some suggestions:

  • Do not use GET parameters to transport the score back to the user. They can be easily manipulated (they only cheat on themselves though, do they?).
  • Use Ajax calls and JavaScript to call the processing page, to not let the User reload the entire game every round.

Final thoughts on your code

In however way you rewrite your game, here is a final tip for you: Do not store your answer in a <input type="hidden"> field. The player could easily read the answer by looking at the source code. Instead, send your input factors to the processing code on the server, and let him do the work. :)

Getting you started

Here is a very basic, working solution to your problem based on your initial code. Remember, this is not how a final solution should look like, but it is intended to provide you with a starting point. Make sure you fully understand it or you will run into trouble very soon!

game.php:

<?php
$factor1 = rand(2, 12);
$factor2 = rand(2, 12);
$score = isset($_GET["s"]) ? $_GET["s"] : 0;
$round = isset($_GET["r"]) ? $_GET["r"] : 0;
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Game</title>
    </head>
    <body>
        <div id="stats">
            <p>Your current score is: <?php echo $score; ?></p>
            <?php if( isset($_GET["l"]) ): ?>
            <p>Wrong answer! The correct solution would have been: <?php echo $_GET["l"]; ?>
            <?php endif; ?>
            <?php if( 5 == $round ): ?>
            <p>Game over! You scored <?php echo $score; ?> points.
            <?php endif; ?>
        </div>
        <div id="form">
            <form method="post" action="processGame.php">
                <?php echo "$factor1 * $factor2 ="; ?>
                <input type="text" name="userInput" maxlength="3" />
                <input type="submit" name="solve" value="Solve">
                <!-- Meta information, used to compute game progress: -->
                <input type="hidden" name="f1" value="<?php echo $factor1; ?>">
                <input type="hidden" name="f2" value="<?php echo $factor2; ?>">
                <input type="hidden" name="s" value="<?php echo $score; ?>">
                <input type="hidden" name="r" value="<?php echo $round; ?>">
            </form>
        </div>
    </body>
</html>

processGame.php:

<?php
//retrieve postet information
$userInput = isset($_POST["userInput"]) ? intval($_POST["userInput"]) : 0;
$factor1   = isset($_POST["f1"])        ? intval($_POST["f1"]) : 0;
$factor2   = isset($_POST["f2"])        ? intval($_POST["f2"]) : 0;
$score     = isset($_POST["s"])         ? intval($_POST["s"]) : 0;
$round     = isset($_POST["r"])         ? intval($_POST["r"]) : 0;
// calculate correct result
$solution  = $factor1 * $factor2;

//this is the url that will be returned to. Notice the use of GET parameters
$url = "game.php?r=".($round+1);

//check with user input
if( $userInput == $solution)
{
    $score += 1;
    $url.="&s=$score";
}
else
{
    $url.="&s=$score&l=$solution";
}
//return to interface
header("Location:$url");
Community
  • 1
  • 1
T3 H40
  • 2,326
  • 8
  • 32
  • 43