Session Variables are Null - php

I've searched and tried over a dozen suggestions from similar issues on this site, but only a little closer to resoluton.
I am starting out with HTML & PHP so this is a very simplistic couple of scripts.
I am setting up an array with math questions (to test my 9 year old son).
The first script "mathtest.php" sets up the array and sets a couple of variables in the $_session global variable and then a form submits an answer to the question to "mathtest1.php".
My $_session variables are lost when I get to "mathtest1.php".
Please help. I know I can do something with cookies, but I really want to advance in my understanding of sessions.
Here's the 2 scripts:
"mathtest.php":
<?php
session_start();
?>
<html>
<title>Math Test</title>
<head>Math Test</head>
<body>
<?php
$arrayindex = 0;
for ($L = 1; $L <= 12; $L++) {
for ($R = 12; $R >= 1; $R--) {
$setupquestions[$arrayindex] = $L.'*'.$R;
$arrayindex++;
}
}
$_session["questions"] = $setupquestions;
$_session["randomkey"] = array_rand($_session["questions"],1);
?>
<form action="mathtest1.php" method="post">
What is <?php echo $_session["questions"][$_session["randomkey"]]." ?" ?>
<input type="text" name="answer">
<input type="submit" name = "submit">
</form>
</body>
</html>
The script above works as expected, but the script below has null values for the session variables I"m trying to access and use.
"mathtest1.php":
<?php
session_start();
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$answer = $_POST['answer'];
$result = eval("return $_session[questions]$_session[randomkey];");
echo "result = ".$result."<br />";
if ($answer == $result) {
echo "Correct!!";
}
else {
echo "WRONG!!";
}
}
$_session["randomkey"] = array_rand($_session["questions"],1);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is <?php echo $_session["questions"][$_session["randomkey"]]." ?" ?>
<input type="text" name="answer">
<input type="submit" name = "submit">
</form>
</body>
</html>
Other details:
OS X, Chrome Browser, latest version of PHP
XAMPP installation & scripts are on the same laptop as XAMPP, not on an external server.
session cookies are ON
...Trans_ID is ON
I have read & write access to the session save path.

$_SESSION should be in uppercase.

try uppercase!
http://php.net/manual/en/reserved.variables.session.php
$_SESSION

Unlike function names...
function bar(){
}
function Bar(){
}
...
Fatal error: Cannot redeclare Bar() (previously declared in C:\tmp\test.php:3) in C:\tmp\test.php on line 7
... variable names are case-sensitive in PHP:
$foo = 1;
$Foo = 2;
$FOO = 3;
var_dump($foo, $Foo, $FOO);
...
int(1)
int(2)
int(3)
This applies to predefined variables as well, including $_SESSION.

Related

What's wrong with this calculation?

Consider this markup:
<?php
$drill = 0;
$result = '';
$dynamicD = rand(5,15);
$num01 = $dynamicD-4;
$placeholder = $num01.'+4';
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["drill"])){
$humanErr = "Empty";
}
else {
$drill = $_POST["drill"];
if($drill !== $dynamicD) {
$result = "No";
}
else {
$result = "Yes";
}
};
};
?>
<!doctype html>
<html>
<body>
<p>Correct Answer: <?php echo $dynamicD ?></p>
<p>Does this work? <?php echo "$result";?></p>
<form method="post">
<fieldset>
<label for="drill">Can you solve it?</label>
<input type="text" name="drill" id="drill" maxlengh="2" placeholder="<?php echo $placeholder ?>" required="true" />
</fieldset>
<button type="submit" name="check">Check</button>
</form>
</body>
</html>
Basically it generates "random" number, insert it as a drill, and then let the user submit his answer. The problem is that the answer is always "NO"*.
I tried to separate the condition to this:
if($drill > $dynamicD) { $result = "bigger" }
elseif ($drill < $dynamicD) { $result = "smaller" }
and so on - but can't understand the logic of the $result (sometime bigger, sometime smaller, but i ALWAYS enter $dynamicD...).
What am i doing wrong here???
EDIT:
As the comments points, every time the page submit it generates new numbers. The first time the code execute is the only time that correct answer would be equal to the numbers that display. After the first submit there is a gap.
Note for future readers: The above code extracted and simplified from bigger and much complex system. Not something that anyone would want to just copy-paste.
The solution i choose was to store the dynamically created vars on a session and re-declare if the answer is correct.
Would love to hear about other ways (not client side).

PHP ... display array (results of survey) using forloop [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 3 years ago.
I am new to PHP and working on an assignment. I'm almost finished but feel like I'm beating my head against the wall with this last step.
The user chooses a survey and then answers 10 questions. After the 10th question is answered, they are redirected to the results.php page which should display their questions and answers.
I know that I need to use a foreach loop but this is my first time working with them. I've finished multiple sites to get an understanding of how they work but the examples are not helping me to understand how to make it work in my assignment.
Right now I get this when I run the file:
Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH), expecting end of file in C:\xampp\htdocs\sandbox\HW4\results.php on line 38
When I remove the endforeach, I'm told that $answer within the echo is undefined.
I've run out of ways to change my loop. Nothing works. Some help would be appreciated. I apologize if I include code that is not relevant to my problem.
With little understanding of PHP, I'm not quite sure what I need to include and what I don't. I'm including code from my survey.php file that includes the array session and my code from the results file that should contain my foreach loop.
Thank you for your time.
$isPostBack = filter_input(INPUT_POST, 'submitButton') !== NULL;
if ($isPostBack) {
// This is what happens if there is a postback.
$choose_survey = filter_input(INPUT_POST, 'choose_survey', FILTER_VALIDATE_INT);
if ($choose_survey !== NULL) {
// Check the value of $choose_survey and then set 'survey' accordingly, e.g.
// These numbers are the keys to the arrays with the list of surveys
switch ($choose_survey) {
case 0:
$_SESSION['survey'] = $survey0;
break;
case 1:
$_SESSION['survey'] = $survey1;
break;
case 2:
$_SESSION['survey'] = $survey2;
break;
default:
break;
}
$_SESSION['answers'] = array();
$_SESSION['number'] = 1;
} else {
// A survey is not selected because it was already chosen.
// get the value from the radio button.
$answer = filter_input(INPUT_POST, 'answer', FILTER_DEFAULT);
if ($answer == NULL) {
echo '<p>Please select an answer before clicking Submit.</p>';
} else {
$question_key = filter_input(INPUT_POST, 'question_key', FILTER_VALIDATE_INT);
$question = $_SESSION['survey'][$question_key];
// this will be used later to display the answers/results
$_SESSION['answers'][$question] = $answer;
unset($_SESSION['survey'][$question_key]);
// This is adding 1 to the question number unless session number is 10
if ($_SESSION['number'] == 10) { // if = to 10 then we redirect to next page.
header('Location: results.php');
} else { // If number is less than 10, we add 1
$_SESSION['number'] += 1;
}
}
}
} else {
// This is what happens if there is no postback.
}
?>
results.php file
<br /> <p>Thank you for participating in the survey!</p>
<html lang="en">
<head>
<title>Survey Results</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<form action="logout.php">
<p>Here are your results</p>
<input type="submit" id="submit" value="Logout" />
</form>
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer) ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php endforeach; ?>
</section>
</body>
did you loaded the session_start() on your file? If not this may not enable to save your sessions that you are setting. Also on your results.php you can change your code to:
<?php foreach($_SESSION['answers'] as $question => $answer){ ?>
<p>
<?php echo $answer."<br/>"; ?>
</p>
<?php }
?>
Hope this helps!
I am not sure, but maybe you could place <?php session_start();?> at the beginning of your results.php to make your script able to work with $_SESSION variable?
Also try to var_dump($_SESSION); as in result.php, just in case.
I surprised that nobody noticed the syntax error in the foreach.
If you want to use the endforeach style, you can change your code like this (this is called Alternative Syntax):
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer): ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php endforeach; ?>
</section>
Or if you want to use PHP-way to make a foreach, you can write it like this:
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer) { ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php } ?>
</section>
However, for cleaner HTML & PHP code, I suggest you to write it like this:
<section>
<?php
foreach ($_SESSION['answers'] as $answer) {
echo "<p>$answer</p>" . PHP_EOL;
}
?>
</section>
Note that I removed unused $question variable.

PHP echo doesn't show up in webpage

So im fairly new in coding HTML CSS and PHP and now im focusing PHP.
Our professor asked us to incorporate PHP codes in our website (no database) and im trying to print a an array using a for loop and echo.
the problem is that the echo doesn't show in the webpage and I am now lost
below is my codes:
<html>
<head>
<title>PHP Loops and Sorts</title>
<body>
<h1>PHP Loops and Sorts</h1>
<div class="container">
<?php
$dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($array,$size){
$size = count($array);
return $size;
}
if(isset($_POST['btnShow']) )
{
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick,$size);
for(&x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
}
?>
Breeds of different kinds of animals. Select what animal's breed to be shown:<br>
<select name="formAnimal">
<option value="">Choose animal</option>
<option value="dogs">Dog</option>
<option value="cats">Cat</option>
<option value="birds">Bird</option>
<option value="fishes">Fish</option>
</select><br><br>
<div style="margin:auto,text-align:center;text-align:center">
<INPUT TYPE = "Submit" Name = "btnShow" VALUE = "Show List"> 
<INPUT TYPE = "Submit" Name = "btnAsc" VALUE = "Show Ascending"> 
<INPUT TYPE = "Submit" Name = "btnDes" VALUE = "Show Descending">
</div>
<?php
echo $size
?>
</div>
</body>
</html>
You need to close your head tag before your body tag.
You also don't need to pass in size to your method count size.
function countsize (&array) {
return count(&array);
}
if(isset($_POST['btnShow']) ) are you sure it is set ?
From what we have in your code you can't even POST, you are missing your form tags
Try wrapping your inputs with :
<form method="POST">
<!--inputs-->
</form>
Your syntax for the for loop is incorrect. Check out the php documentation
Also the $size variable is never declared in the scope you are using it.
Didn't get how you're using $arrsize but you used &x instead of $x while initializing loop.
for($x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
change this lines of code:
$dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($array,$size){
$size = count($array);
return $size;
}
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick,$size);
for(&x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
To :
$animalArray['dogs']=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$animalArray['cats']=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$animalArray['birds']=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$animalArray['fishes']=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($index){
return count($animalArray[$index]);
}
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick);
for($x = 0;$x<$arrsize;$x++){
echo $animalArray[$arraypick][$x] . "<br>";
}

PHP Static variable reloads after Page Load

This is a simplified version of what I want to accomplish:
In my script I want a static variable x to be incremented every time the submit button is pressed.
<?php
function IncX(){
static $x = 0;
$x++;
echo $x;
}
?>
<body>
<form>
<input type="submit" name="submit" class="next btn btn-primary" value="Submit" />
</form>
</body>
But it initializes to x=0 on every page reload after submit.
You're loading the variable afresh every time the page loads, so it's always going to be the same.
The solution is to store it in a session and then increment it there. Include a conditional to create the variable if it doesn't already exist.
<?php
session_start();
if (!isset($_SESSION['x'])) {
$x = $_SESSION['x'];
} else {
$x = 0;
}
$x++;
echo $x;
$_SESSION['x'] = $x;
?>
<?php
session_start();
$x = 0;
if (isset($_SESSION['x'])) {
$x = $_SESSION['x'];
$x++;
} else {
$_SESSION['x'] = $x;
}
// /$x++;
echo $x;
$_SESSION['x'] = $x;
?>
Apache doesn't keep track of variables in php scrips between clicks, you would have to store it somewhere, be it the $_SESSION or a database.
Moreover, the static keyword doesn't do what you seem to think it does. It would work for successive calls of the function in a single run of the script, but not between clicks.
in any event, you can use the ternary operator to achieve this, would you happen to put it in the session. I've also added a check to make sure the variable is actually a viable count number:
session_start();
$_SESSION['x'] = isset($_SESSION['x']) && is_int($_SESSION['x'])
? $_SESSION['x'] + 1
: 1;
echo $_SESSION['x'];

My $_SESSION variable will not hold its value. Any Ideas on why?

I want it to increment and decrement the value in $_SESSION['selection'].
Mousedown on next form results in: "The session is 1".
Mousedown on previous form results in "The session is -1".
Here is the code:
<?php
if (isset($_POST['next'])) {
displaynext();
}
else if (isset($_POST['previous'])) {
displayprevious();
}
else {
session_start();
echo "session started";
$_SESSION['selection'] = 1;
}
function displaynext() {
$_SESSION['selection'] = $_SESSION['selection'] + 1;
echo "The session is $_SESSION[selection]";
}
function displayprevious() {
if ($_SESSION['selection'] != 1) {
$_SESSION['selection'] = $_SESSION['selection'] - 1;
}
echo "The session is $_SESSION[selection]";
}
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="previous" value="Previous">
</form>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="next" value="Next">
</form>
Put the session_start() call on the beginning of your file; right after the <?php open tag. You also need to do that on every script that you plan to use sessions.
By the way, instead of writing:
$_SESSION['selection'] = $_SESSION['selection']-1;
$_SESSION['selection'] = $_SESSION['selection']+1;
You can use
$_SESSION['selection']--;
$_SESSION['selection']++;
Read: Increment/Decrement operators
Make sure you're using session_start() on every page you use your session on.
Put the session_start call to the beginning of your code, outside of any conditions.
session_start needs to be called in every script you're using the session in, not just at the very beginning (ie. the first pageload).
You're not calling session_start when moving between pages. Move the call to before the if statements, like this:
session_start();
if(isset($_POST['next'])) {
displaynext();
} else if(isset($_POST['previous'])) {
displayprevious();
} else {
echo "session started";
$_SESSION['selection'] = 1;
}

Categories