How to get first page to equal 1 everytime - php

Below I have a line of code where it states which Page a user is currently on out of the number of Total Pages.
<h1>CREATING QUESTIONS AND ANSWERS: SESSION (AAA) <?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?></h1>
So for example the line could read this:
CREATING QUESTIONS AND ANSWERS: SESSION (AAA) 3 OF 3
Now the problem I have is that if the user is on the first page, it doesn't display the number 1. So instead of stating 1 OF 3 or 1 OF 5, it is stating 2 OF 3 or 2 OF 5.
So my question is that how can I get the first page to equal 1 OF ... when user accesses the first session (first page)?
Below is the current code:
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = $_POST['sessionNum'];
$_SESSION['sessionCount'] = 0;
}
else if ($_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
$sessionMinus = $_SESSION['sessionCount'];
$_SESSION['sessionNum'] is the total number of Sessions. So if it is 3 OF 5, then $_SESSION['sessionNum'] is 5.

if you want to build something like "Wizards" then in sessions you would store some data to keep track of user activity and general process, you say "if the user is in the first session ..." that's confusing, better say "if the user is in first step"
say you want to store in sessions, "user is in step 1 of 3 total steps", you would need
$_SESSION["user_track"] = array(
("current") => 1,
("next")=>2,
("total") => 3,
("previous") => 0
);
and a IF to check on every step
if($_SESSION["user_track"]["next"] != $GLOBAL_STEP){
/*
$GLOBAL_STEP , a integer you defined in the current step say its 2
and users next step matches 2 then he/she is on the correct step
*/
}else if($_SESSION["user_track"]["next"] == $_SESSION["user_track"]["total"]){
/*At the ending step*/
}else{
// couldn't proceed to next step, something went wrong
}
hope it helps

I would suggest :
to use the word 'page' or 'steps' instead of 'session', because 'session' is confusing with the $_SESSION array.
to use a simple GET parameter for current page/step (e.g. yourpage.php?step=X), where by default the step value would be 1.

Related

Using Sessions for keeping score has a vulnerability on page reload that can be used to exploit score

First here is a quick preview of how my program works. I have a PHP quiz in which if a user gets an answer right it is set to display certain things including the addition of points to the users score and it also reloads the page and displays the next question. If the user guesses wrong the same thing happens but it subtracts score instead. All of this works fine however, I did find one major vulnerability which is that if the user reloads the page it will return to the first question but it will keep the current score. So if you are on question 4 with 40 score and you need to reload the page it does set you back to the first question as it should but it keeps that 40 score.
Now I cannot do something where on page reload it resets the score because my quiz after a question is answered right or wrong reloads the page to display the next question. This would then mean that the session would end after every question which is not what I want and the whole purpose of me using session is to keep the scoring when it reloads to the next question. Now my first thought was to create an if statement that checked whether or not the question was back to 1 (which happens after a page reload) it would reset the score to 0. I tried this however it does not reset the score back to 0 rather it still stays counting up. Here is the code I tried:
if($currentQuestion==1){
$_SESSION['score'] == 0;
}
Now here is the code in the entirety of my PHP. I feel like including little snippets of sections may not give a full look at the depth of my program and what I am trying to solve so I am just going to post it in its entirety (I will be excluding the arrays though as they are not needed to show it):
<?php
session_start();
$questionsAndAnwsers = array(array("question" => " What early cartoon character created by the Disney Studio was Mickey Mouse based off of ?", "answer" => "Oswald The Lucky Rabbit"),
//rest of arrays were here ignore this comment
$_SESSION["count"];
if (!isset($_SESSION['score'])) {
$_SESSION['score'] = 0;
}
// current question
$currentQuestion = 0;
if(isset($_POST["currentQuestion"])){
$currentQuestion = $_POST["currentQuestion"];
if(isset($questionsAndAnwsers[$currentQuestion])){
$currentAnswer = $questionsAndAnwsers["$currentQuestion"] ["answer"];
if($currentQuestion==15){
session_destroy();
header("Location: http://students.purchase.edu/martin.mcnicholas/scriptingfortheweb/loginmain.html"); /* Redirect browser */
exit();
}
else if($_POST["guess"] == $currentAnswer){
$currentQuestion++;
$guess = $_POST['guess'];
print ("<span class='Stylize2'>Your answer: $guess <br>");
print("The answer expected: $currentAnswer<br>");
print("Answer Correct $answerCorrect<br><br>");
$images = [
1 => 'MickeyMouse.png',
2 => 'Philo.jpg',
3 => 'warner.jpg',
4 => 'superman.jpg',
5 => 'own.jpg',
6 => 'scooby.png',
7 => 'garfield.jpg',
8 => 'pok1.jpg',
9 => 'peanuts.jpg',
10 => 'sam.jpg',
11 => 'haim.jpg',
12 => 'back.jpg',
13 => 'joe.jpg',
14 => 'r.png',
15 => 'wild.jpg',
];
if( array_key_exists($currentQuestion, $images))
echo "<img src='{$images[$currentQuestion]}' alt='$images[$currentQuestion]' height='200'><br><br>";
else
echo "Not found";
$_SESSION['score']+=10;
echo $_SESSION['score'];
print(" points");
echo "<br>";
print("Next Question Below<br></span><br><br>");
}
else {
$currentQuestion=0;
$guess = $_POST['guess'];
print ("<span class='Stylize'>Your answer: $guess <br>");
print("You have failed..<br>");
echo '<img src=angry.gif height="200"><br><br>';
$_SESSION['score']-=5;
echo $_SESSION['score'];
print(" points");
echo "<br><br>";
echo "</span>";
$test = '251993__kwahmah-02__distorted-voice-18.wav';
echo '<audio autoplay loop>';
echo "<source src='$test' type='audio/wav'>";
echo 'Your browser does not support the audio element';
echo '</audio>';
}
}else{
exit("Question not found!");
}
if($currentQuestion==1){
$_SESSION['score'] == 0;
}
}
?>
I did leave the if statement that is not working in to show you all where it is placed. I also understand this is a lot of code and if anyone has any edit suggestions to trim it down well then do suggest but for now since I don't know what I should exclude I am showcasing it all.

how to display the number 1 each time user accesses the page

I have a problem when it comes to displaying the correct number in my heading. When a user submits a page and navigates to this current page, I want the heading below to appear:
CREATING QUESTIONS AND ANSWERS: SESSION (AAA) 1 OF 3
As you can see it above it starts with the number 1 as the user is creating their first session. The problem I am getting is that it never displays number 1, it just keeps displaying this below:
CREATING QUESTIONS AND ANSWERS: SESSION (AAA) 3 OF 3
It keeps displaying the number 3 which is incorrect as if the user enters the current page for the first time then obviousl they don't start with session 3, they start with session 1, then 2 then 3.
So my question is how do I get "SESSION 1" to be displayed when the useer enters the page for the first time?
Below is the current code I have:
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = $_POST['sessionNum'];
}
if (!isset($_SESSION['sessionCount'])) {
$_SESSION['sessionCount'] = 1;
}
else if ($_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
++$_SESSION['sessionCount'];
}
$sessionMinus = $_SESSION['sessionCount'];
...
<h1>CREATING QUESTIONS AND ANSWERS: SESSION (<?php echo $_SESSION['id'] ?>) <?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?></h1>
When you are setting for the first time:
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
Set it to 1! Because after that isset will return true, and so, it will not be set to 1...
//Declare my counter for the first time
$_SESSION['initial_count'] = 1;

How to stop adding a number when it reaches its limit

<?php
session_start();
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = $_POST['sessionNum'];
}
if(!isset($_SESSION['sessionCount'])){
$_SESSION['sessionCount'] = 1;
}
else
{
$_SESSION['sessionCount']++;
}
$sessionMinus = $_SESSION['sessionCount'];
?>
How do I get it so that if $_SESSION['sessionCount'] is less than $_SESSION['sessionNum'], then add 1 to $_SESSION['sessionCount'] and if it equals $_SESSION['sessionNum'], then stop adding 1 to $_SESSION['sessionCount']?
Also if I go back on a previous page and I go back onto this page, I want $sessionMinus to go back to '1', and finally if the user refreshes the page, then whatever number $sessionMinus is, keep it on that number when page refreshes.
How do I get it so that if $_SESSION['sessionCount'] is less than
$_SESSION['sessionNum'], then add 1 to $_SESSION['sessionCount'] and
if it equals $_SESSION['sessionNum'], then stop adding 1 to
$_SESSION['sessionCount']?
if (!isset($_SESSION['sessionCount'])) {
$_SESSION['sessionCount'] = 1;
}
else if ($_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
++$_SESSION['sessionCount'];
}
Also if I go back on a previous page and I go back onto this page, I
want $sessionMinus to go back to '1'
To do that you have to set $_SESSION['sessionMinus'] (or some other variable) in the previous page. Once this page is reached, the only way to know what happened earlier is specifically through $_SESSION variables. You cannot detect it on the spot.
and finally if the user
refreshes the page, then whatever number $sessionMinus is, keep it on
that number when page refreshes.
This is not possible. You cannot tell if the page was refreshed or loaded from scratch¹. What you could do is use the PRG pattern and count the "P" page as "the user just got here" and the "G" page as "the user has refreshed the page". You can set a variable (e.g. $_SESSION['redirecting'] = true) from the "P" page and modify it on the "G" page ($_SESSION['redirecting'] = false); just before you do that, check if it was true to begin with. If it was, then the user is here due to your redirect (which will only happen once). If it was already false, they have refreshed the page.
¹You can try to do it, again through $_SESSION, but really you are just guessing. There is no way to know for certain.
if ($_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
// sessionNum is bigger then sessionCount
$_SESSION['sessionCount']++;
}

how to set variable on previous page back to 1

I have some variable where everytime the form is submiited or page is refreshed, it adds 1 to $sessionMinus. But if the user goes onto the previous page and then goes back onto this page, I want $sessionMinus to go back to being '1'.
At the moment if lets say the number is 3 and then the user goes back to previous page and then back to this page, it still displays 3, but I want it to go back to 1. I heard I have to set either $sessionMinus or $_SESSION['sessionCount'] to '1' on the previous page but how do I do this?
below is the code for the current page (not previous page) on how the $sessionMinus is declared and incremented:
if(!isset($_SESSION['sessionCount'])){
$_SESSION['sessionCount'] = 1;
}
else
{
$_SESSION['sessionCount']++;
}
$sessionMinus = $_SESSION['sessionCount'];
?>
On the previous page, do:
if( isset( $_SESSION['sessionCount'])){
$_SESSION['sessionCount'] = 1;
// Or maybe 0 if you want $sessionMinus = 1 on next page
}

Very strange $_SESSION behaviour

I have a Session which I am using to hold items in a form that are accumulated up by the user until the user wants to proceed to checkout. Its a bit like a Shopping cart where items can be added from the form.
Logical breakdown of code:
Page loads, session starts
If $_SESSION['set'] is not set then set it to TRUE.
Display rest of page and form.
User hits "Add another item" button.
Page data gets posted to itself
Page checks that $_SESSION['set'] = True and $_POST['add_item'] is set.
Page creates a session variables in an array, and adds posted values to those sessions.
Page increments $_SESSION['tariff_count'] if more needs to be added
The problem is that my code is not behaving as it should. When I click "Add new tariff" button the first time it does not get caught by my if function. This should be immediately caught. However when I go and press the button again, it finally works and adds an item to my session.
Here is the code:
//start a session to remember tariff items
session_start();
//testing the session array
print_r($_SESSION);
//destroy session if this character is found in URL string
$des = $_GET['d'];
if($des == 1)
{
session_destroy();
}
//checks to see if session data has been set
//if a session variable count is set then
if ($_SESSION['set'] == TRUE)
{
//perform a check to ensure the page has been called by the form button and not been accidently refreshed
if(isset($_POST['add_tariff']))
{
//if user clicks Add another tariff button then increase tariff count by one
//temp variable set to the current count of items added
$count = $_SESSION['tariff_count'];
$_SESSION['tariff_name'][$count] = $_POST['tariff_name'];
$_SESSION['tariff_net'][$count] = $_POST['tariff_net'];
$_SESSION['tariff_inclusive'][$count] = $_POST['tariff_inclusive'];
$_SESSION['tariff_length'][$count] = $_POST['tariff_length'];
$_SESSION['tariff_data'][$count] = $_POST['tariff_data'];
//increment tariff count if more data needs to be added to the sessions later.
$_SESSION['tariff_count']++;
}
}
//if no session data set then start new session data
else
{
echo "session set";
$_SESSION['set'] = TRUE;
$_SESSION['tariff_count'] = 0;
}
The code seems to be fudging my arrays of Sesssion data. All my added items in the session are displayed in a table.
However if my table shows six items, if i do a print_r of the session it only shows there are 4 items in the array? I have tested it to make sure I am not reprinting the same instances in the array.
Here is a print_r of the array that shows six rows but there are only four rows in this array?
[tariff_count] => 5 [tariff_name] => Array (
[0] => STREAM1TARIFF [1] => STREAM1TARIFF [2] => CSS [3] => CSS [4] => CSS
)
I have take a screenshot as well to show this strange problem
http://i.imgur.com/jRenU.png
Note I have echoed out "True Value =6" but in the print_r of the session it is only 5, so my code is missing out one instance (n-1).
Here is my code that prints all the instances in the session arrays, I have a feeling part of the problem in mismatch is caused by the "<=" comparison?
if(isset($_SESSION['tariff_count']))
{
for ($i = 0; $i <= $count; $i++)
{
echo "<tr>";
echo "<td>".$_SESSION['tariff_name'][$i]."</td>";
echo "<td>".$_SESSION['tariff_net'][$i]."</td>";
echo "<td>".$_SESSION['tariff_inclusive'][$i]."</td>";
echo "<td>".$_SESSION['tariff_length'][$i]."</td>";
echo "<td>".$_SESSION['tariff_data'][$i]."</td>";
echo "</tr>";
}
}
Paste bin of php page - http://pastebin.com/petkrEck
Any ideas, why my If statement is not catching the event when the user presses "Add another tariff" button the first time it is pressed, but then detects it afterwards?
Thanks for your time
Merry Christmas!
The problem is your code flow. In simplified pseudo-code, you're doing this:
if (session is not initialized) {
set = true
count = 0;
} else {
add posted data to session
}
On the first 'add item' call, the session is not set up, so you set up the session. AND THEN IGNORE THE POSTED DATA.
The code flow should be:
if (session is not initialized) {
set = true;
count = 0;
}
if (posting data) {
add data to session
}

Categories