PHP Trivia Game using sessions - php

I am creating a trivia game, how it works:
A person goes to the index page.
The system generates him a random question out of the array.
The user answers the questions
If question is right, system will echo 'Correct answer' and will generate a new question.
If question is not equal to answer in the array, system will echo 'Wrong answer' and will generate a new question.
I have done the part of question generations, but I am having problems with the matching answers - Considering if you answer a question, after you click submit, the question automatically changes so your answer will be incorrect unless the randomQuestion stays the same.
My friend told me I need to use sessions for the random questions part, but nothing else.
I am not really sure how would I do this, I am really lost.
This is my code:
Question generation
<?php
session_start();
$questions = array(array('What is Google?', 'god'),
array('What is God?', 'gode'),
array('Why is god?', 'godee'));
$randomQuestion = array_rand($questions);
$question1 = $questions[0][0];
$question2 = $questions[1][0];
$question3 = $questions[2][0];
if ($randomQuestion == 0 && !isset($_SESSION['question1'])) {
echo $question1;
} else if ($randomQuestion == 1 && !isset($_SESSION['question2'])) {
echo $question2;
} else if ($randomQuestion == 2 && !isset($_SESSION['question3'])) {
echo $question3;
}
?>
Form + matching answers
This script is currently only checking for question 1 as a test.
<form action="index.php" method="post">
<input type="text" name="answer">
<input type="submit" value="Answer it!">
</form>
<?php
$answer = $_POST['answer'];
if (!empty($answer)) {
if ($randomQuestion == 0) {
if ($answer == $questions[0][1]) {
echo 'Correct Answer!';
unset($_SESSION['question1']);
unset($_SESSION['question2']);
unset($_SESSION['question3']);
}
} else {
echo 'Answer is incorrect.';
return;
}
} else {
echo 'Field is empty';
return;
}
session_destroy();
?>
What I have thought of:
After reading much articles about sessions, I thought about checking if randomQuestion is isset, if it's isset, then it won't generate new questions.
After you answer the question, it will unset the random question so the system can generate a new question.
But it didn't really work as I didn't do it right.
What did I do wrong?
And what is the easiest way to do this?
Thanks!

I wouldn't start by using sessions. Of course I may end up using them but for a proof of concept it's best to do it the simple way first.
All you really need to do is insert a hidden value into your form that will tell you the question number.
For example (not tested):
<?php
$questions = array(
array('What is Google?', 'god'),
array('What is God?', 'gode'),
array('Why is god?', 'godee')
);
$rnd=mt_rand(0,count($questions)-1);
$question=$questions[$rnd];
echo($question[0]);
?>
<form action="index.php" method="post">
<input type="hidden" name="q" value="<?=$rnd?>">
<input type="text" name="answer">
<input type="submit" value="Answer it!">
</form>
The rest of the server code to verify the question and answer I'll leave as an exercise.

If you want this trivia game to be played by more that one person (and I suppose you do) , you need to come up with something more that a simple < form > ... You must store the answers one user gives so that the other user can see them.

Related

Form validation with a php array

I'm hoping someone could help me finish off some php code (the avon guy already kindly helped me with this but I'm still struggling with the last bit).
All it is, is I have a form where I have 10 particular sequences of digits, which if entered, allows the form to redirect to the following page. If anything else is entered I want the page to deny access with some kind of error prompt.
At top of the php, in the part before any php is printed, avon guy suggested an array to check the 10 correct sequences against.
$possibles = array('rva858', 'anothersequence', 'andanother');
$match = $_POST['nextpage'];
if (array_search($match, $possibles) != false) {
//match code in here
} else {
// fail code in here
}
I'm not sure what to put in the //match code in here AND the //fail code in here, bits. Can someone help me with this last bit please?
Many thanks
Jon
If you are just trying to redirect to another page using php, you can use header('Location: mypage.php');. More information on header here.
So for your code example (edited based on comment):
invitation.php
<?php
//invitation.php
$possibles = array('rva858', 'anothersequence', 'andanother');
$match = $_POST['nextpage'];
if (array_search($match, $possibles) === false)
{
//If fail
header('Location: formpage.php?errorMessage=Incorrect code!');
exit();
}
//If success:
//All of the invitation.php html and success code below
formpage.php
<?php
//formpage.php
if(!empty($_GET['errorMessage'])){
echo '<span>' . $_GET['errorMessage'] . '</span>';
}
?>
<form action="invitation.php" method="post">
<input name="rsvp" type="text" />
<input type="submit" value="Submit" name="submit" />
</form>

How to use if & else to find an answer in an array?

I am having a problem with simple PHP app where a user has to enter a correct answer from a list of available options. And that options are stored in an array. The problem is that i cannot use the options anytime in the script other than the array declaration point. I might sound dumb...and i am, believe me. Lets say this is the array:
$hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");
Now there is a text box in my script and $_POST method is used to submit the form. The correct choice which i have selected is 'Sports'. Now there are 4 possibilities a user might click submit, they are listed below.
A user clicks the submit button without entering any text in the textbox.
A user guesses the wrong choice which is from the $hobbyChoices but not 'Sports'.
A user guesses a choice which is not from the array. i.e anything other than what is in the array.
Finally, the user enters the correct choice that is 'Sports'.
This might seem pretty easy but the problem is that i cant use the names of the hobbies anywhere in the script, as mentioned before, other than the array declaration. Can i please get help? Also, when i tried to do one of the 4 possibilities, i encountered a problem with the uppercase and lowercase. This is seriously getting irritating, any help would be greatly appreciated.
Thanks!
If I am understanding your question correctly, the following is what you are looking for:
<?php
$hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");
if (isset($_POST['answer'])) {
$answer = mysql_real_escape_string($_POST['answer']);
$correct_answer = $hobbyChoices[4];
$response = "Your answer is not one of the answers listed!";
foreach ($hobbyChoices as $value) {
if (strtolower($answer) == strtolower($value) && (strtolower($answer) != strtolower($correct_answer))) {
$response = "You selected the wrong answer from the list of options!";
}
else if (strtolower($answer) == strtolower($value) && (strtolower($answer) == strtolower($correct_answer))) {
$response = "You have answered correctly!";
}
}
print $response;
}
?>
<form name="form" method="post">
<table>
<tr>
<td>What is baseball?
</td>
<td><input type="text" name="answer" />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="submit" />
</td>
</tr>
</table>
</form>
strtolower is a function in php that converts strings to lowercase and would help you compare your two values.

give a user X number of chances to input a value in PHP

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 !!!

Why rand() every time I refresh the page?

I want to run mini program for confirmation security question :
$questions = array('dog legs','car legs','the best country in the world');
$answers = array(4,4,'USA');
$questionId = rand(0, (count($questions)-1));
and then
$ans = $_POST['answer'];
if($ans == $answers[$questionId]){echo 'Confirmed !';}
So the prob is that not every time that I answer the answer is correct, because after sending form the rand function runs and changes the question ! Any solutions ?
You can pass in the form an hidden input with as value the question ID, that way the id will be resent.
<input type="hidden" name="questionId" value="<?php echo $questionId; ?>"></input>
Then check if the form is submitted.
<?php
if ($_POST['questionID'])
$questionID = $_POST['questionID'];
else
$questionID = rand(0, (count($questions)-1));
You can also secure all this by using base64 encoding
Best way:
Basicly you need to save the question id into the users session.
Workaround:
If thats to complicated, do the following.
Create a secret string.
Create md5 from secret string + correct answer.
Write the md5 into a form hidden field.
On form submission, check if the secret string + given answer returns the md5 from the form.
Unless someone knows your secret string, you are safe even without sessions.
Attention
My workaround has the same problem than storing the question ID into the form like sugegsten in another answer: One could simply manipulate the question ID to always show a once-solved question. Session is the only more or less safe way
Best regards
Zsolt
You'll need to know what the original question was as well. Easiest way to do that would be just to post the question in the form as a hidden input :
<form>
<?php echo $questionID; ?>
<input type="text" name="answer" />
<input type="hidden" name="question" value="<?php echo $questionID; ?>" />
</form>
and do
$questions = array('dog legs','car legs','the best country in the world');
$answers = array(4,4,'USA');
$questionID = rand(0, (count($questions)-1));
if (isset($_POST['answer'])) {
$answer = $_POST['answer'];
$question = $_POST['question'];
if ( $questions[ $question ] == $answer ) // you're golden
}

Updating hidden input depending on what user has checked

I've created a test system that has multiple steps (using jquery) allowing users to check checkboxes to select their answers, with a summary page and a final submission button... all within a form. I now want to create the scoring system.
1) Firstly this is the code (within a loop) that grabs the answers from Wordpress for each question:
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo $row['answer']; ?>" />
2) In Wordpress next to each answer is a dropdown with a yes or no option to mark whether the answer is right or wrong. This is output in the following way:
<?php $row['correct']; ?>
3) Each correct answer the user checks should be worth 1 point. The passmark is determined by the field:
<?php the_field('pass_mark'); ?>
4) I want it to update a hidden field with the score as the user checks the correct answer:
<input type="hidden" value="<?php echo $score; ?>" name="test-score" />
How can I update the hidden field with the user score as the user is checking the correct answer? I'm not sure what to try with this to even give it a go first!
Ok, everyones spotted a big hole in this. I'm completely open to doing it a hidden way so people can't check out the source. The type of user this is targeted at wouldn't have a clue how to look at the source but might as well do it the right way to start with!
The whole test is within a form so could it only update the hidden field on submit?
I still need some examples of how to do it.
In my opinion you should use sessions for that purpose, because any browser output may be saved and viewed in ANY text editor. This is not right purpose oh hidden input elements. You use hidden inputs when you need to submit something automatically, but never use it when processing some important data.
Mapping your questions and answers via id will allow you not to reveal real answers and scores in HTML.
Just a very simple example how to do that:
<?php
$questions = array(
125 => array("text"=>"2x2?", "answer"=>"4", 'points'=>3),
145 => array("text"=>"5x6?", "answer"=>"30", 'points'=>2),
);
?>
<form method="post">
<?php foreach ($questions as $id => $question): ?>
<div><?php echo $question['text'] ; ?></div>
<input type="text" name="question<?php echo $id ; ?>"/>
<?php endforeach ; ?>
<input type="submit" value="Submit"/>
</form>
/* In submission script */
<?php
if (isset($_POST['submit'])){
foreach($questions as $id => $question){
if (isset($_POST["question{$id}"])){
$answer = $_POST["question{$id}"] ;
if ($answer === $question['answer']){
$_SESSION['score'] += $question['points'] ;
}
}
}
}
Spokey is right - the user would be able to cheat if your score it on the client side like using the method you suggested.
Instead, either user a JQuery $.post call to post each answer and then store the score in a PHP Session. Or just wait until the entire form is submitted and evaluate the score of the form as a whole on the server side.
* Update *
You have to submit the form to a script that can evaluate the form. So say it gets submitted to myForm.php
In myForm.php, get the post vars:
$correct_answers = $however_you_get_your_correct_answers();
//Assuming $correct_answers is a associative array with the same keys being used in post -
$results = array();
if($_POST){
foreach ($_POST as $key=>$value) {
if ($_POST[$key] == $correct_answers[$key]){
$results[$key] = 'correct';
}
else $results[$key] = 'incorrect';
}
}
This is untested, but it should work.

Categories