PHP multiple sessions - php

Why am I getting only the last session's output when printing ? I need to save a session for each user id and send a password reset email. when user clicks the link and change the password I need to clear the session from server.
This is how I am doing it with PHP.
$res = array();
$uniqueId = uniqid();
echo $uniqueId . "<br>";
session_id($uniqueId);
session_start();
echo session_id() . "<br>";
$_SESSION['session_id'] = session_id();
$_SESSION['event_id'] = 'event1';
$_SESSION['user_id'] = 'user1';
$res[] = json_encode($_SESSION);
$uniqueId2 = uniqid();
echo $uniqueId2 . "<br>";
session_destroy();
session_id($uniqueId2);
session_start();
echo session_id() . "<br>";
$_SESSION['session_id'] = session_id();
$_SESSION['event_id'] = 'event2';
$_SESSION['user_id'] = 'user2';
$res[] = json_encode($_SESSION);
echo "<br>";
print_r($res);
output of the print_r:
Array (
[0] => {"session_id":"5609187f586da","event_id":"event1","user_id":"user1"}
[1] => {"session_id":"5609187f588e1","event_id":"event2","user_id":"user2"}
)
Now in a new page when I am trying to each the event id of both sessions like this, I only get the last session's event_id but not the both. for the first it says
Notice: Undefined index: event_id in C:\xampp\htdocs\test\test.php on line 12
This is what i am doing in new page.
$id1 = '560915a8c0875';
$id2 = '560915a8c0d51';
session_id($id1);
session_start();
echo $_SESSION['event_id'];
echo "<br>";
session_id($id2);
echo $_SESSION['event_id'];
Is this not possible with PHP or what?

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.
http://php.net/manual/en/function.session-destroy.php
When calling session_destroy on $id1 the data will also be cleared from the server meaning when you define the session id to $id1 it will return an empty session.

Related

PHP Session is null when accessed in a different script

I'm setting a session like so:
// ---- Start the session
session_start();
.
.
.
.
$tokenMap = $_SESSION["tokenMap"];
$date = new DateTime();
$created = $date->getTimestamp();
$accessToken = uniqid();
if (!isset($tokenMap))
$tokenMap = array($accessToken=>array("username"=>$username, "created"=>$created));
else {
// ---- Unset any values that already exist
foreach($tokenMap as $t => $user) {
if ($user["username"] === $username) {
unset($tokenMap[$t]);
break;
}
$tokenMap[$accessToken] = array("username"=>$username, "created"=>$created);
}
echo $_SESSION["tokenMap"]; // returns correct values
However, when I access it in a different script, $_SESSION is empty:
// ---- Start the session
session_start();
echo json_encode($_SESSION); // []
Is there something I'm missing or misunderstanding about PHP sessions?
To make your session available you can create a table and save & update your session data when ever you need.

PHP opens 2nd session unwanted

Requirement: use QRBOT-app to scan a barcode on a mobile and give the number scanned to the website.
Problem: I've a session open (1), from here I'm opening the app (see ScanBardcode.php), I scan and the app returns to the callback-URL including the required parameters. However I do expect it is re-using it's session, it creates a new one (2). Can someone help me? It does have both sessions active and both pages keep using it's own session. I can only test it on my cell phone, which I checked is using each time (the initiate-1 and the callback-2 the same browser)
What I tried already:
1. Pass the sessionID in the callback URL (QRBOT doesn't allow parameters)
2. Set Session.auto_start to 1
ScanBarcode.php
<?php
include_once('../../config.inc.php'); //contains DB connection details and other settings
include_once($fullurl . '../../admin/includes/sessie.inc.php'); //generates session
echo "SessionID=". session_id() . "!";
$_SESSION['BarCode'] = "VoorraadTellen";
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
//URL to open qrbot.
echo "click"
?>
ScanBarcodeCallBack.php
<?php
$source = $_GET['x-source'];
$content = $_GET['content'];
$format = $_GET['format'];
include_once('../../config.inc.php');
include_once($fullurl . '../../admin/includes/sessie.inc.php');
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
echo "SessionID=". session_id() . "!";
echo $source . $content . $format;
// HERE I WRITE TO THE DB.
?>
sessie.inc.php
<?php
$a = session_id();
if(empty($a))
{
session_start();
}
if(isset($_SESSION['sgebruiker']))
{
$now = time();
if($now - $_SESSION['stijd'] > $_SESSION['maxidle'])
{
$_SESSION = array();
session_destroy();
}
else
{
$_SESSION['stijd'] = $now;
}
}
elseif(isset($_COOKIE['login_cookie']))
{
//Check against db and set cookie.
}
?>
Adding screenshot when I add the sessionId in the URL as a parameter:
enter image description here
Update to ScanBarcode.php
`echo "click"
as far as i know you don't need the whole check with session_id(). PHP Documentation for session_start() says:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
this is also my experience. every time i used session_start() i just put it at the top of every file (or included it like you did)
When you pass the session ID in the URL, you need to use the parameter to set the session ID before calling session_start(). Change sessie.inc.php to:
<?php
if (isset($_GET['s'])) {
session_id($_GET['s']);
}
session_start();
if(isset($_SESSION['sgebruiker']))
{
$now = time();
if($now - $_SESSION['stijd'] > $_SESSION['maxidle'])
{
$_SESSION = array();
session_destroy();
}
else
{
$_SESSION['stijd'] = $now;
}
}
elseif(isset($_COOKIE['login_cookie']))
{
//Check against db and set cookie.
}
?>
Working with both #Tsai and #Barmar we found the solution.
We fixed it by:
- Encoding the URL by using urlencode-function
- Take the sessionID from URL and apply that using session_id-function before initiating the start_session (see also).
The cleaned up code below; hopefully someone would be able to use it also.
ScanBarcode.php
<?php
include_once('../../config.inc.php'); //contains DB connection details and other settings
include_once($fullurl . '../../admin/includes/sessie.inc.php'); //generates session
echo "SessionID=". session_id();
//URL to open qrbot.
$CallbackUrl = "http://ilonashairstyling.nl/2016UAT/module/Ilonas_admin/ScanBarcodeCallBack.php?s=" . htmlspecialchars(session_id());
echo "click"
?>
ScanBarcodeCallBack.php
<?php
$source = $_GET['x-source'];
$content = $_GET['content'];
$format = $_GET['format'];
include_once('../../config.inc.php');
ini_set("session.use_cookies",0);
ini_set("session.use_trans_sid",1);
session_id($_GET['s']);
//print_r($_SESSION); //You can test it with this code
//print(session_id()); //You can test it with this code
ini_set("session.use_cookies",1);
ini_set("session.use_trans_sid",0);
include_once($fullurl . '../../admin/includes/sessie.inc.php');
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
echo "SessionID=". session_id() . "!";
echo $source . $content . $format;
// HERE I WRITE TO THE DB.
?>
sessie.inc.php is unchanged

Session data lost after page redirect

I'm having problems getting simple session data values to persist after a page redirection. A function checks user data sent via Post and if it matches values in a database it sets session data to the values and redirects to another page:
if ($login_ok) {
//set session data
$_SESSION ['online'] = 1;
$_SESSION ['userid'] = $id;
$_SESSION ['username'] = $name;
//redirect to new page
redirect('start.php');
}
In the new page code the session data is not set. Simple testing returns null values as if the session data wasn't set:
echo 'Session Login Status: ' . $_SESSION ['online'];
echo 'Session UserID: ' . $_SESSION ['userid'];
echo 'Session Username: ' . $_SESSION ['username'];
Replacing the redirect with the above echo statements works correctly. Is the fact that the session data is set and the redirect activated before any page data has loaded mean that the session variables are not assigned?
To ensure an active session is always available, an include file contains this code:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Any idea what the issue is here?
Many thanks,
Kw
Check if the session is set before progress with
if isset($_SESSION ['online']) and
isset($_SESSION ['userid']) and
isset($_SESSION ['username'])
{
echo 'Session Login Status: ' . $_SESSION ['online'];
echo 'Session UserID: ' . $_SESSION ['userid'];
echo 'Session Username: ' . $_SESSION ['username'];
} else {
echo 'Redirect to login or Session expired';
}
Instead of redirect try this
$uid = $_SESSION['USERID'];
if (isset($uid) || $uid != NULL)
{
if (!headers_sent()) {
header('Location:main.php');
exit;
}
else {
?>
<script>window.location = 'main.php';</script>
<?php
}
}
This seems to be a server rather than a code issue. Running the code on a localhost server works correctly. Hope this is helpful to people experiencing similar issues.
Saying that, I have no idea how to set the remote server to allow session data. The server has browser based web administration software called cPanel, any suggestions?

PHP Session Variables are not passed to next page

I have 2 PHP pages in the same folder. I am trying to set a session variable on one page (test.php), then read its value on another (test2.php). However, the session variable gets lost on the second page.
test.php
<?php
session_start();
$_SESSION["test"] = "123hello";
$hello = $_SESSION["test"];
echo "out: $hello";
$sid = session_id();
echo "<br> sid: $sid";
?>
test2.php
<?php
session_start();
$hello = "test";
if(isset($_SESSION["test"]))
{
$hello = $_SESSION["test"];
}
echo "out: $hello";
$sid = session_id();
echo "<br> sid: $sid";
?>
First I visit test.php, which outputs:
out: 123hello
Then I visit test2.php, which outputs:
out: test
Which means in test.php, the session variable does keep its value. However, for some reason it gets lost in test2.php.

PHP cookie value not being passed from one page to another

This is in a page called headersessioncookie.php
<?php
session_start();
if ( ! isset ( $_SESSION['loggedin'] ) ) {
$_SESSION['loggedin'] = FALSE;
}
$expiry = time()+60*60*9000;
setcookie('cookie[loggedin]', '', $expiry, "", "", "", TRUE);
if ( ! isset ( $_COOKIE['cookie[loggedin]'] ) ) {
$_COOKIE['cookie[loggedin]'] = FALSE;
}
?>
This is in a page called test.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
$_SESSION['loggedin'] = TRUE;
$_COOKIE['cookie[loggedin]'] = TRUE;
?>
When I run test.php and then run this page below called test1.php ...
<?php
require_once('headersessioncookie.php'); //start session and cookie
echo "sessionvalue" . $_SESSION['loggedin'] . '<br>';
echo "cookievalue" . $_COOKIE['cookie[loggedin]'] . '<br>';
?>
... I get
sessionvalue1
cookievalue
Why don't I get...
sessionvalue1
cookievalue1
...??
The superglobal variable $_COOKIE only contains the cookie values. If you modify this value won't affect to the cookie because you need to sent the headers to the browser to do so.
If you need to modify it you have to use the method setCookie because this will sent the headers with the new value.
Note Remember that the $_COOKIE only will be updated after use setCookie when you refresh the page.
So this should work:
File: headersessioncookie.php
<?php
//Session
session_start();
if ( !isset($_SESSION['loggedin']) )
$_SESSION['loggedin'] = FALSE;
//Cookie
$expiry = time()+60*60*9000;
if ( !isset($_COOKIE['cookieloggedin']) )
setcookie('cookieloggedin', '', $expiry, "", "", true);
?>
File: test.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
$_SESSION['loggedin'] = TRUE;
setcookie('cookieloggedin', '1', $expiry, "", "", true);
?>
File: test1.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
echo "sessionvalue" . $_SESSION['loggedin'] . '<br>';
echo "cookievalue" . $_COOKIE['cookieloggedin'] . '<br>';
?>
Please notice also:
-How to update a cookie: https://stackoverflow.com/a/6487597/3933332
-Is a Cookie Case Sensitive: https://stackoverflow.com/a/11312272/3933332
Answering my own question. Turns out there were 3 major problems with my code.
1) I was trying to set the cookie value by doing this:
$_COOKIE['cookie[loggedin]'] = FALSE;
Turns out one needs to use setcookie() to set the cookie value. Assigning a new value to $_COOKIE will change the value of that variable (within the scope of the same page), but it won't change the value inside the cookie (outside the scope of that page, calling $_COOKIE will yield the value stored in the cookie).
2) The following is incorrect
echo "cookievalue" . $_COOKIE['cookie[loggedin]'] . '<br>';
Instead it should be
echo "cookievalue" . $_COOKIE['cookie']['loggedin'] . '<br>';
3) Cookie necessarily has to be passed a string value. I was trying to pass a value = FALSE which is not a string. Instead, I could have correctly passed a value = 'FALSE'

Categories