How can I manage the lifetime of my PHP sessions? - php

I am quite new to PHP, so I'm working on a simple project to practise. However, I can't manage to make the session management work properly.
What I want is that when the browser is closed, the data (the current page the user is at) is saved for an hour. If the user returns within an hour, he should see the same page he left, and if he return after an hour, he should see the first question.
When all questions have been answered, he should see a score-screen, with a "Try Again" button that preferably destroys/kills/deletes the session and starts a new one, directing the user to the first question.
If I leave out line 3-8 my code works as expected, I run throught the questions until I get stuck at the score-screen with a non-working "Try Again" button, I can only go back to the first question by closing and reopening the browser.
With these lines, the page runs through the questions fine but when I restart the browser, it starts at the first question. When I close the browser without doing anything and open the page a second time, I find the page I left at first. I close and open the browser again and I find the correct page again, I do it again and I'm back to question 0. No matter how often I then restart the browser, I stay at question 0.
When I look at the cookies in my browser, I have the same cookie all the time, one that started at 14 december 2015 18:48:45. However, the experation time isn't correct either, as that is 26 november 2061 13:37:29, instead of an hour later. What am I doing wrong?
Here is my code:
<?php
/* Sart (new) session*/
if (isset($_GET['TryAgain'])){
session_start();
$_SESSION = array();
session_destroy();
}
session_set_cookie_params(time()+3600);
session_start();
/*-------------------------------------------------------------------*/
/* IMPORT DATABASE: $qs[i]=question text, $as[i]=array(choices per question),
$as[i][i]=array('t'=>choice text, 'c'=>BOOLEAN) */
require_once('config.php');
$dbh = new PDO("mysql:dbname=$db;host=$host", $user, $password);
$questions = $dbh->prepare('select * from questions');
$questions->execute();
$choices = $dbh->prepare('select * from choices');
$choices->execute();
$qs = array();
$as = array();
foreach($questions as $row) {
$i = $row['q_nr'];
$qs[$i] = $row['q_text'];
}
foreach($choices as $row) {
$qi = $row['q_nr'];
$ci = $row['c_nr'];
$as[$qi][$ci] = array('t'=>$row['c_text'],'c'=>$row['correct']);
}
/*-------------------------------------------------------------------*/
/*INITIALIZE SESSION VARIABLES*/
/* Creates counter-variable if not set -------- (ini value is 0)*/
if(!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
}
/* Creates score-variable if not set -------- (ini value is 0)*/
if(!isset($_SESSION['score'])) {
$_SESSION['score'] = 0;
}
/*-------------------------------------------------------------------*/
/* SET COUNTER, SCORE AND DONE*/
/* Check if answer previous question has been submitted*/
if (isset($_GET['a'])) {
$submitted = true;
} else {
$submitted = false;
}
/* Set counter*/
if ($submitted){
$_SESSION['counter'] += 1;
}
$cqi = $_SESSION['counter'];
/* Set score*/
if ($submitted) {
if ($as[$cqi-1][$_GET['a']]['c']){
$_SESSION['score'] += 1;
}
}
$score = $_SESSION['score'];
/* Check done*/
if($cqi >= count($qs)){
$done = true;
} else {
$done = false;
}
echo 'cqi: '.$cqi;
echo 'done: '.$done;
/*-------------------------------------------------------------------*/
?>
<!-- START HTML!!! -->
<html>
<head>
</head>
<body>
<br><br>
<?php
if($done){
echo 'You finished the quiz. <br> Your score is: '.$score;
echo "<form action='index.php' method='get'>";
echo "<input type='hidden' name='TryAgain' value=true>";
echo "<input type='submit' value='Try again!'>";
echo "</form>";
} else {
echo $qs[$cqi];
echo "<form action='index.php' method='get'>";
$cci = 0;
foreach($as[$cqi] as $cc){
echo "<input type='radio' name='a' value=".$cci.">".
$cc['t']."<br>";
$cci++;
}
echo "<input type='submit' value='Next question'>";
echo "</form>";
echo "<br><br>Current score: ".$score;
}
?>
</body>
</html>
Please help me, I really am stuck with this.
-Edit-
I tried again omitting line 3-8 and keeping session_set_cookie_params(600);, to test this function as simply as possible. I tested it the same way as cited above, reopening my browser time and time again and noting down which question I got (q. 0 or 1). I got a seemingly random pattern, of first question 0 and the question I should be on, 1, in which 0 is often the most prevalent. I am quite sure it is random, as I removed the cookie and redid the test multiple times and each time I saw a different pattern. The cookie does expire now at the right time though.
I also tried the ini_set('session.cookie_lifetime', 600); instead of session_set_cookie_params(600); function, as suggested in the other question, but I still had random results. And I don't think it is a good idea for me to try and create a login system if I even can't get this right...

Related

$_GET doesn't work in my program and no lines beneath it are executed

I am trying to add a function to my website where it will add filters to a SQL select statement by allowing the user to enter text in some text boxes and clicking the filter button.
I haven't gotten as far as that because I'm having issues with the $_GET function.
The idea is that if the query parameters are set, it will use them in the sql statement and if not, it will just return all the rows.
Below is the displayListings function which is called every time the page is loaded.
Although I'm showing the whole function, I havent implemented most of it because nothing works past the line where I use $_GET.
<?php
function displayListings() {
global $dbConnection;
//checks if the query parameters exist
if (isset($_GET['title'])) {
echo 'got here... :F';//for debugging
var_dump($_GET['title']);//for debugging
$title_filter = $_GET('title');// THIS IS THE LINE THAT THE SCRIPT STOPS AT
var_dump($title_filter);//for debugging
}
//checks if the query parameters exist
if (isset($_GET['artist'])) {
$artist_filter = $_GET('artist');
echo $artist_filter."/n";
}
//checks if the query parameters exist
if (isset($_GET['release'])) {
$release_filter = $_GET('release');
echo $release_filter."/n";
}
echo 'here!';
// connect to the database
if (!connectToDb('musiconline')) {
$_SESSION['errorMsg'] = "Sorry, we could not connect to the database.";
header('location:listItem.php');
exit();
}
// after this point we have an open DB connection
// gets the current highest ID so we know what the next should be.
$sqlQuery = "SELECT listingid, recordtitle, artist FROM vinyl";
$result = $dbConnection->query($sqlQuery);
if (!$result) {
$_SESSION['errorMsg'] = "There was a problem with the database: " . $dbConnection->error;
closeConnection();
header('location:listItem.php');
exit();
}
//gets the results and puts them in a rows array
while($row = $result->fetch_array()){
$rows[] = $row;
}
//iterates through each row of the results (each vinyl)
foreach($rows as $row){
$listingID = $row['listingid'];
$recordTitle = $row['recordtitle'];
$artist = $row['artist'];
echo '
<div class="listing">
<table class="tableception">
<tr><td><img src="uploads/vinyl'.$listingID.'.png" alt="img1" ></td><td>
<table class="listing-table">
<tr><td>Album title: </td><td>'.$recordTitle.'</td></tr>
<tr><td>Artist name: </td><td>'.$artist.'</td></tr>
</table>
</td></tr>
</table>
</div>
' . "\n";
}//END OF FOREACH
/* free result set */
$result->close();
/* close connection */
closeConnection();
}
?>
When I debug the page in my IDE, everything works fine, probably because there are no query parameters in the URL.
The page stops loading after the $_GET line, as seen below.shows screenshot of browser when query parameters exist in URL.
I just cant figure out what I'm doing wrong.
Thanks in advance.
I used curly brackets instead of square brackets in the line.
I had $title_filter = $_GET('title');
instead of $title_filter = $_GET['title'];
Thanks #AymDev for pointing this out to me!

php variable on separate page not working

Can anyone help on this please. It's driving me crazy!
I have on one page:
foreach($images_not_on_server_unique as $img => $missing){
foreach($test as $m => $n){
foreach($n as $o => $p){
$query1 = "SELECT * FROM $p WHERE adv='$missing'";
$result1 = mysqli_query($conn,$query1) or die(mysqli_error());
$numofrows = mysqli_num_rows($result1);
if($numofrows >= '1'){
$row1 = mysqli_fetch_array($result1);
$errors_images++;
}
}
}
}
echo $errors_images;
which correctly prints out '16'.
On another page I include the page, and then echo the variable from the first page like so:
echo "errors images ".$errors_images;
which should give me '16'. However, I get only 'errors images'.
What am I doing wrong. I have used include many, many times before and it has always worked (but maybe not in a foreach loop). I have tried using $GLOBALS, but to no avail.
Many thanks for any help.
EDIT
The full code for the second page
<?php
include("login/include/session.php");
include("dbconnect/index_new.php");
require("errors/q_errors.php");
include_once("errors/q_missing_images.php");
echo "errors images ".$errors_images;
?>
UPDATE:
I have added
$my_test = '555';
to the first page and echoed it in the second page with
echo "my test ". $my_test;
and it works correctly!
Therefore it must have something to do with the foreach function in the first page.
Either you're including the file incorrectly
include_once 'path/to/file.php';
Or you're calling it incorrectly
echo 'errors images'.$errors_images.'';

PhP Change a variables value from front end?

Hello everyone and thanks for your time in advance!
I am trying to finish a project for my university and I am missing something really small.. So basically I have a variable in which I have set a specific value and as a front end user(as the Administrator of that page) I want to make a change on that value. It's like the following.. I have a specific number set and I want to be able to edit/update the value of it from a text box, or somehow from the browser.
Lets say I have this as source code:
$row = 0;
$totalpeoplenumber = 50;
$peoplenumber = 0;
$sql="SELECT peoplenumber FROM bookingform";
$result = mysqli_query($con, $sql) or die ("ERROR 01".mysqli_error($con));
foreach($result as $result_data => $result_row)
{
echo $result_data['peoplenumber'];
$peoplenumber += $result_row['peoplenumber'];
}
echo ('<h2>Seats Availability</h2>');
echo ("<br>");
echo ('<b>Reserved Seats number: </b>');
echo $peoplenumber."<br>";
echo ("<br>");
$totalpeoplenumber = $totalpeoplenumber - $peoplenumber;
echo "<b>The number of available seats is: $totalpeoplenumber</b> </br></br>";
echo "<button>Edit total seats</button>";
So here I need to somehow change the value of $totalpeoplenumber as the administrator of the webpage and not as a programmer.
Thanks a lot.
For sake of simplicity you can do something like:
if(isset($_GET['totalpeoplenumber')){
$totalpeoplenumber = $_GET['totalpeoplenumber '];
}
Then in your browser all you have to do is use the address: localhost/myAdminPage.php?totalpeoplenumber=60
it will set the total number of people to 60.
Note that you don't have to edit the URL itself, you can use a form where the submit sends to the same page (in that case you should use POST instead of GET):
<form action="myAdminPage.php" method="GET">
Insert the totalpeoplenumber: <input type="text" name="totalpeoplenumber"/>
<input type="submit" value="Send"/>
</form>
This propably will do for the form. In your script all you have to do is put the following code:
if(isset($_POST['totalpeoplenumber'])){
$totalpeoplenumber = $_POST['totalpeoplenumber'];
}
done :)

what means these examples about session fixation?

the first example
<?php
session_start();
if(!isset($_SESSION['count'])) $_SESSION['count'] = 0;
else ++$_SESSION['count'];
echo $_SESSION['count'] . "<br />";
?>
the second example
<?php
session_start();
if(!isset($_SESSION['initiated']))
{
session_regenerate_id();
$_SESSION['initiated'] = 1;
}
if(!isset($_SESSION['count'])) $_SESSION['count'] = 0;
else ++$_SESSION['count'];
echo $_SESSION['count'] . "<br />";
I can find the only different is if I use two different URLs(eg: http//localhost/test?PHPSESSID=123; http//localhost/test?PHPSESSID=456) the first script will count up again from zero, but the second will continue count
so what do two examples mean? and what does it want to tell me?
Sorry, my first answer was too hasty. Check This out. PHP.net says:
"session_regenerate_id() will replace the current session id with a new one, and keep the current session information."
session_regenerate_id() if it can, will submit a cookie to keep the session details.
Think of it as a extended session for the user. So that if the user closes their browser, the user session can be recalled.

Display records from database one at a time on a single webpage

I current have the following records of questions in my database.
|QuestionID|QuestionText|
|1|What is the HTTP port number?|
|2|What is the Telnet port number?|
|3|What is the FTP port number?|
I would like to display each question one at a time on a single webpage using PHP scripting.
The user can view the next question by clicking on the 'next' button.
I would also like to include 'previous' button to allow the user to go back to the previous page.
In addition to this, how can I determine the amount of time the user spent on each of the question (QuestionID)?
Even if I tried using the following loop method of clicking next to view the next question but I am also having problems viewing the next question,what is wrong ?
if(isset($_POST['next']))
{
$a=$_POST['a'];
}
if(!isset($a))
{
$a=0;
}
echo $a;
$questionquery="SELECT * FROM QuestionBank Limit 1 OFFSET $a ";
$questionresult=mysql_query($questionquery) or die ('Query failed:'. mysql_error());
echo "<form method='post' action=''>";
while ($row = mysql_fetch_array($questionresult))
{
echo $row['QuestionText'];
}
$a = $a+1;
echo "<input type='hidden' value='$a' name 'a'>";
echo "<input type='submit' name='next' value='next'>";
From question 1 to 3, it's just pagination.
You can use : http://www.phpeasystep.com/phptu/29.html. Just edit some parts and you're good to do.
For question 4, you can just use time() at the start of the webpage. And when the user go to the next page, you can set time() again and get the time difference.
Hope this help out a little(:

Categories