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
Related
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.
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?
I have an application that works TOTALLY fine on my local server.
It requires two things:
An active $_SESSION so that a number of key data elements are available on every page. (Stuff like user_id, and user_role.)
A couple of "require_once()" calls at the top of my pages, so that I have some constants available and standard messages available and the same header on every page.
Again, on my local server (using php 5.6), this is all fine and dandy.
On my HOST server (also using php 5.6), however, I have a catch-22:
If I call "session_start()" on each of my pages, I get a "headers already sent" warning, due to my use of "require_once()".
If I do NOT call "session_start()" on each of my pages, the $_SESSION variable is empty when it gets to the next page.
The only ideas I have seem very bad:
Don't use sessions and pass all my data in the URL. This seems insecure, clumsy, and like bad practice.
Don't use "require_once()", which seems really stupid as I'll have duplicate code all over the place.
Any ideas about what I should do?
I am on a shared server, so I don't think I can modify the php.ini file. And my host company, who has been very helpful about any other issue, has been totally silent over the past 2 weeks as I've sent them questions about this.
I have created a very simple example that shows the issue. Probably the most informative bit is in the comments for "firstpage.php", specifically the "if" statement under the comment "Under what circumstances is session being started".
Here is the index page (called mytestindex.php).
<?php
// Make sure $_SESSION array is available.
session_start();
//***************************************************
// Print to the screen information about the session
// This sends headers on the host server.
//***************************************************
require_once("printsessioninfo.php");
// Set SESSION variable for later use on other pages
$_SESSION['emp_id'] = 100;
echo "\n\nThe employee id stored in SESSION is: " . $_SESSION["emp_id"] . "\n\n";
// Open next page when button clicked.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Set the name of the page we are going to next
$filename = "firstpage.php";
// ***************************************************************************************************
// If headers have't been sent (seems to depend on php.ini settings), simply call the header function
// This is the code that has worked on my local machine for years.
// ***************************************************************************************************
if (!headers_sent()) {
$redirect_to = "Location:" . $filename;
exit(header($redirect_to));
// *******************************************************************************************************************
// If headers have already been sent (require_once() above will do that), using the header function
// will generate a "headers have already been sent" warning on the host server. So need to use Javascript to avoid that.
// ********************************************************************************************************************
} else {
echo " Opening page with Javascript. ";
$code = '<script type="text/javascript">';
$code = $code . 'window.location.href="' . $filename . '";';
$code = $code . '</script>';
$code = $code . '<noscript>';
$code = $code . '<meta http-equiv="refresh" content="0;url=' . $filename . '" />';
$code = $code . '<noscript>';
echo $code;
exit;
}
}
?>
<div>
<form action="mytestindex.php" method="post">
<button type="submit">Go to first page</button>
</form>
</div>
Here is the page it links to (called firstpage.php):
<?php
/* First page */
//***************************************************
// Print to the screen information about the session
// This sends headers on the host server.
//***************************************************
require_once("printsessioninfo.php");
//***********************************************************************
// Print out other information before session started again on this page
if (headers_sent()) {
echo "Headers have already been sent.\n";
} else {
echo "No headers have been sent.\n";
}
if (isset($_SESSION)) {
echo "Session variable exists.\n";
} else {
echo "Session variable does not exist.\n";
}
//*****************************************************
// Under what circumstances is session being started
// and does it cause a "headers already sent" warning?
//*****************************************************
// THIS check is what works on my local machine, with no warnings about headers being sent.
if ( (!isset($_SESSION)) && (!headers_sent()) ) {
echo " START SESSION: session var is not set AND headers have not been sent.";
session_start();
} elseif (session_status == PHP_SESSION_NONE) {
echo " START SESSION: session does not exist";
session_start();
// THIS check is what works on my host server, BUT throws the warning about headers being sent.
} elseif (!isset($_SESSION)) {
echo " START SESSION: session var is not set";
session_start();
} else {
echo " No need to start a new session";
}
//******************************************************************************
echo "\n\n The employee id stored in the session variable is: " . $_SESSION["emp_id"] . " .";
if (session_status() == PHP_SESSION_ACTIVE) {
echo "\n\n\n NOW Session is active!";
}
?>
Here is a snippet of code that prints out some session info, so I have demonstrate how "require_once()" affects things (called printsessioninfo.php):
<?php
// Print session info
echo "<pre>";
$sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id();
echo 'session file: ' . $sessionfile . ' ';
echo 'size: ' . filesize($sessionfile) . "\n\n\n";
if (session_status() == PHP_SESSION_NONE) {
echo "Session does not exist!\n";
} elseif (session_status() == PHP_SESSION_DISABLED) {
echo "Session is disabled!\n";
} elseif (session_status() == PHP_SESSION_ACTIVE) {
echo "Session is active.";
}
?>
I was able to fix this (thank you "mister martin"), by moving the code for "session_start()" into my config.php file, making sure it was the VERY FIRST bit of code.
Then for every page in the application I made sure this was the first line of code:
<?php
require_once("config.php");
And that did the trick, for both development and host servers.
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Explanation required as it seems it wasn't clear enough (??):
If the status of the session is NONE then start it.
http://php.net/manual/en/function.session-status.php
http://php.net/manual/en/session.constants.php
Also this should be called BEFORE any require or require_once
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
I need a little help with my script, I am making a library sign in/out and page and I have it working so that it posts the form when they sign in and out, but i want to make it to where if they are trying to sign out and they actually never signed in it would pop-up a js alert tell them that and I can't quite get it.
Here's the code:
<?php
session_start();
include_once("connect.php");
date_default_timezone_set("America/Winnipeg");
$date = ("m-d-Y");
$timeout = date("g:i:s a");
//search for existing entries
if ("SELECT EXISTS(SELECT * FROM signin_out WHERE
lname='".$_POST['lastname']."' AND fname='".$_POST['firstname']."'
AND date='".$date."')") {
//if they exist run this
mysql_query("UPDATE signin_out SET timeout='" . $timeout . "'
WHERE lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "' AND timeout='' ");
header("Location: ../index.html");
//if they don't exist run this
} else {
header("Location: ../index.html");
echo "<script type='text/javascipt'>\n";
echo "alert('You did not sign in!');\n";
echo "</script>";
}
?>
The HTTP Location header already sends them to ../index.html long before the JavaScript gets echoed out. You need to have a logout.php page with that JavaScript or a $_GET variable for the page you redirect them to, and trigger the alert box there.
For instance:
...
} else {
header('Location: ../index.php?notloggedin');
}
And somewhere in your index.php:
<?php
if(isset($_GET['notloggedin'])) {
echo '<script>alert("You did not sign in!");</script>';
}
?>
Although I find that an alert box is rather intrusive, I'd rather do:
<?php
if(isset($_GET['notloggedin'])) {
echo '<p><strong>You did not sign in!</strong></p>';
}
?>