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.
Related
I was having issues with the session file being locked, so I added session_write_close() once I was done with the session. The script worked properly before that, however, once I leave the sign-in page now, the session is blank.
Session is started at the top of index.php which includes the sign in page:
$result = 'token_valid';
$_SESSION['user'] = $email;
print_r($_SESSION);
session_write_close();
print_r($_SESSION);
The session data is returned properly both times on the sign-in page.
Array ( [user] => abc#gmail.com ) Array ( [user] => abc#gmail.com )
A link returns to the home page, which calls a function to check if logged in...
function user_is_signed_in() {
print_r($_SESSION);
session_write_close();
if($user == '') {
return False;
}
else {
return True;
}
}
The session no longer has any data.
Full index.php
<?php
session_start();
include_once('fnc/database.php');
include_once('fnc/user.php');
if(!user_is_signed_in()) {
include('sign-in.php');
}
else {
$url = parse_url($_SERVER['REQUEST_URI']);
if(!$url['query'])
{
include('home.php');
}
else {
if(isset($_GET['media']))
{
include($_GET['media'].'.php');
}
if(isset($_GET['user']))
{
include($_GET['user'].'.php');
}
}
}
.
.
Workaround (probably filthy)
Issue seems to be caused by the reading/writing of the actual session file. Used the session_id generated by PHP and just created a secondary session file. Do not save in same folder (or if you do, change the filename) - session_start seems to delete and regenerate the session file PHP manages and you'll lose any data written there.
session_start();
$sess = array();
$sess = $_SESSION;
$sess["id"] = session_id();
//print_r($sess);
session_write_close();
Create session_data in session folder
$session_details = "user|".$email;
$session_file = "/Programs/XAMPP/tmp/session_data/sess_".$sess["id"];
//echo $session_details;
$fh = fopen($session_file, 'w+');
fwrite($fh, $session_details);
fclose($fh);
Read session data from this file instead of the session
$session_path = "/Programs/XAMPP/tmp/session_data/sess_".$sess["id"];
$fh = fopen($session_path, 'r');
$session_file = fread($fh, filesize($session_path));
$exploded_session = explode("\n", $session_file);
$session_data = array();
foreach($exploded_session as $line)
{
$tmp = explode("|", $line);
$session_data[$tmp[0]] = $tmp[1];
}
return $session_data["user"];
fclose($fh);
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
I'm develop a hybrid application and it will using PHP sessions to save user information. In my case, I tried to used php sessions to save the data, but it doesn't save. And then, to testing in web, the result var is show saved.
Here is my example:
<?php
session_start();
if(isset($_POST["Token"])){
$token = $_POST["Token"];
if (isset($_SESSION['device_token']) && $_SESSION['device_token']) {
$token = $_SESSION['device_token'];
} else {
$_SESSION['device_token'] = "notoken";
}
}
?>
Here is my PHP info:
My php Info 1
My php Info 2
Edit:
<?php
ini_set('session.save_path',$_SERVER['DOCUMENT_ROOT'] .'/phpVar');
session_start();
if(isset($_POST["Token"])){
$token = $_POST["Token"];
$_SESSION['device_token'] = $token;
}
if(isset($_GET['ID'])){
$token = $_SESSION['device_token'];
$member_id = $_GET['ID'];
$_SESSION['ID'] = $member_id;
echo $_SESSION['device_token'] ;
echo $_SESSION['ID'] ;
}
?>
because you missed the }
so, instead of:
if(isset($_POST["Token"])){
$token = $_POST["Token"];
should be:
if(isset($_POST["Token"])){
$token = $_POST["Token"];
}
EDIT
Ok, then try to see whether you session directory is writable:
if (!is_writable(session_save_path())) {
echo "No, it's not. Path:".session_save_path();
}
else{
echo "yes, it's writable";
}
EDIT
when path is not set, you might set it manually just before session_start
ini_set('session.save_path',getcwd(). '/tmp');
and afterwards you need to create tmp folder and give it right permission
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.
I am writing a custom session handler and for the life of me I cannot get a cookie to set in it. I'm not outputting anything to the browser before I set the cookie but it still doesn't work. Its killing me.
The cookie will set if I set it in the script I define and call on the session handler with. If necessary I will post code. Any ideas people?
<?php
/* require the needed classes comment out what is not needed */
require_once("classes/sessionmanager.php");
require_once("classes/template.php");
require_once("classes/database.php");
$title=" "; //titlebar of the web browser
$description=" ";
$keywords=" "; //meta keywords
$menutype="default"; //default or customer, customer is elevated
$pagetitle="dflsfsf "; //title of the webpage
$pagebody=" "; //body of the webpage
$template=template::def_instance();
$database=database::def_instance();
$session=sessionmanager::def_instance();
$session->sessions();
session_start();
?>
and this is the one that actually sets the cookie for the session
function write($session_id,$session_data)
{
$session_id = mysql_real_escape_string($session_id);
$session_data = mysql_real_escape_string(serialize($session_data));
$expires = time() + 3600;
$user_ip = $_SERVER['REMOTE_ADDR'];
$bol = FALSE;
$time = time();
$newsession = FALSE;
$auth = FALSE;
$query = "SELECT * FROM 'sessions' WHERE 'expires' > '$time'";
$sessions_result = $this->query($query);
$newsession = $this->newsession_check($session_id,$sessions_result);
while($sessions_array = mysql_fetch_array($sessions_result) AND $auth = FALSE)
{
$session_array = $this->strip($session_array);
$auth = $this->auth_check($session_array,$session_id);
}
/* this is an authentic session. build queries and update it */
if($auth == TRUE AND $newsession == FALSE)
{
$session_data = mysql_real_escape_string($session_data);
$update_query1 = "UPDATE 'sessions' SET 'user_ip' = '$user_ip' WHERE 'session_id' = '$session_id'";
$update_query2 = "UPDATE 'sessions' SET 'data' = '$session_data' WHERE 'session_id = '$session_id'";
$update_query3 = "UPDATE 'sessions' SET 'expires' = '$expires' WHERE 'session_id' = '$session_id'";
$this->query($update_query1);
$this->query($update_query2);
$this->query($update_query3);
$bol = TRUE;
}
elseif($newsession == TRUE)
{
/* this is a new session, build and create it */
$random_number = $this->obtain_random();
$cookieval = hash("sha512",$random_number);
setcookie("rndn",$cookieval,$expires,'/');
$query = "INSERT INTO sessions VALUES('$session_id','0','$user_ip','$random_number','$session_data','$expires')";
$this->query($query);
//echo $cookieval."this is the cookie <<";
$bol = TRUE;
}
return $bol;
}
code updated. still no luck
for some reason if any html is echoed after the session manager is started the cookie is called after the html. this doesnt make any sense to me
The problem is likely in your if/else statements. You are using:
if($auth = TRUE AND $newsession = FALSE)
...
elseif($newsession = TRUE)
The use of a single = means that you are assigning values, not comparing them. You need to use == instead of =.
Change to this:
if($auth == TRUE AND $newsession == FALSE)
...
elseif($newsession == TRUE)
With the code that you have right now, the first if block of your code will run every time, so your setcookie() call is never reached.
setcookie() returns false if php can't add the header. So for debugging try something like
setcookie("rndn",$cookieval) or die('setcookie failed');
You can combine that with a test whether setcookie() is called in the first place
$rc = setcookie("rndn",$cookieval);
/* DEBUG-code don't forget to remove me */
error_log(sprintf("%s %s\n", date('Y-m-d H:i:s setcookie():'), $rc?'success':'failed'));
(or even better use a debugger like xdebug and e.g. netbeans as frontend).
Did you check the response headers in your browser? E.g. via the firebug extension. Perhaps the client receives the cookie header but doesn't accept it.
According to tour code, at least you have to set / directory in the cookie parameters.
But anyway, first of all you have to sniff cookies from the HTTP log. You can use Firebug to watch if server does set any cookie and if browser send any back