This has been driving me nuts for 4 hours. I set a session var at login and later I want to change its value like thus:
session_start();
if (isset($_SESSION) && isset($_POST)) {
unset($_SESSION['columns']);
$_SESSION['columns'] = $_POST['columns'];
}
header('Location: '. $_SERVER['HTTP_REFERER']);
Then when I got back to the referrer page the session var 'columns' has the original value set at login, what gives?
The following variation works fine but back on referrer its back to the old value:
session_start();
$_SESSION['columns'] = $_POST['columns'];
//header('Location: '. $_SERVER['HTTP_REFERER']);
echo "SESSION[columns]=" . $_SESSION['columns'];
echo "<BR>POST[columns]=" . $_POST['columns'];
Related
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
So I've ran into a weird problem that's occurring sometimes when I submit forms. Occasionally after a form is submitted some session objects stop being detected on next page.
I include this at the top off all my pages for the login \ timeout security and it seems to be to problem (as when I remove it everything works fine) but I can't for the life of me figure out what the heck is going on. It's especially weird because it doesn't log me out, but session variables like group_id which I store when you log in stop working.
session_start();
if(isset($_SESSION["CREATED"])) {
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
session_unset();
session_destroy();
$link = "https://" . $_SERVER["SERVER_NAME"] . "/";
header('Location: ' . $link, true, 301);
} else {
$_SESSION['LAST_ACTIVITY'] = time();
}
} else {
$link = "https://" . $_SERVER["SERVER_NAME"] . "/";
header('Location: ' . $link, true, 301);
}
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'm trying to find a way to redirect a user to the page they selected if they have been forced to log in again after a session timeout.
Right now, after the user logs in, they are redirected to index.php. But, if a user received a link in an email to a different section of my site and they have not logged in all day, they are obviously asked to log in but end up on the index.php instead of the page the link was for.
Here is a snippet of my code in the login page:
if (mysql_num_rows($result_set) == 1) {
// username/password authenticated
// and only 1 match
$found_user = mysql_fetch_array($result_set);
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['username'] = $found_user['username'];
$_SESSION['last_activity'] = time();
$_SESSION['time_out'] = 7200; // 2 hours
redirect_to("index.php");
Any ideas would be helpful.
I want to thank everyone who answered my question. The solution was a combination of a few suggestions I received here. I'd like to share with you how I solved this:
Part of the reason why I was having trouble saving the url the user tried to go to before being forced to log in again was that my sessions are handled by an external php file which takes care of confirming login and expiring current session. This file is required by all pages on my website. HTTP_REFERER would not work because it would always be set to the login.php. Here's what I did on my session.php file:
session_start();
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https')
=== FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
$currentUrl = $protocol . '://' . $host . $script . '?' . $params;
if ($currentUrl != "http://domain.com/login.php?") {
$expiryTime = time()+(60*5); // 5 mins
setcookie('referer',$currentUrl,$expiryTime,'/');
}
Essentially, I saved the referring url in a cookie that is set to expire in 5 minutes, giving the user enough time to login. Then, on login.php I did this:
if(isset($_COOKIE['referer'])) {
redirect_to($_COOKIE['referer']);
} else {
redirect_to('index.php');
}
And, BINGO! Works every time.
Try this:
$actual_link = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
if($actual_link == 'the email link'){
header('Location: '. $actual_link);
}else{
header('Location: index.php');
}
Try to save the URL in session whenever a user hit any url like http://www.abc.com/profile.php
once the user has successfully logged in redirect the user to saved URL(which is in session)
it the previous page is in the same directory and then you can try header('Location : .') or else if you if you need to redirect somewhere else.save the path before that situation occurs and in $url then u can redirect using header('Location: $url') or header('Location $url?values')
I'm using PHP 4.3.9, Apache/2.0.52
I'm trying to get a login system working that registers DB values in a session where they're available once logged in. I'm losing the session variables once I'm redirected.
I'm using the following code to print the session ID/values on my login form page and the redirected page:
echo '<font color="red">session id:</font> ' . session_id() . '<br>';
echo '<font color="red">session first name:</font> ' . $_SESSION['first_name'] . '<br>';
echo '<font color="red">session user id:</font> ' . $_SESSION['user_id'] . '<br>';
echo '<font color="red">session user level:</font> ' . $_SESSION['user_level'] . '<br><br>';
This is what's printed in my browser from my login page (I just comment out the header redirect to the logged in page). This is the correct info coming from my DB as well, so all is fine at this point.
session id: 1ce7ca8e7102b6fa4cf5b61722aecfbc
session first name: elvis
session user id: 2
session user level: 1
This is what's printed on my redirected/logged in page (when I uncomment the header/redirect). Session ID is the same, but I get no values for the individual session variables.
session id: 1ce7ca8e7102b6fa4cf5b61722aecfbc
session first name:
session user id:
session user level:
I get the following errors:
Undefined index: first_name
Undefined index: user_id
Undefined index: user_level
I have a global header.php file which my loggedIN.php does NOT call, though loggedOUT.php does - to toast the session):
header.php
<?php
ob_start();
session_start();
//if NOT on loggedout.php, check for cookie. if exists, they haven't explicity logged out so take user to loggedin.php
if (!strpos($_SERVER['PHP_SELF'], 'loggedout.php')) {
/*if (isset($_COOKIE['access'])) {
header('Location: www.mydomain.com/loggedin.php');
}*/
} else {
//if on loggedout.php delete cookie
//setcookie('access', '', time()-3600);
//destroy session
$_SESSION = array();
session_destroy();
setcookie(session_name(), '', time()-3600);
}
//defines constants and sets up custom error handler
require_once('config.php');
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
some page layout stuff
Login portion is eventually called via include
footer stuff
My loggedIN.php does nothing but start the session
<?php
session_start();
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
The logic of my login script, the key part being I'm fetching the DB results right into $_SESSION (about half way down):
if (isset($_POST['login'])) {
//access db
require_once(MYSQL);
//initialize an errors array for non-filled out form fields
$errors = array();
//setup $_POST aliases, clean for db and trim any whitespace
$email = mysql_real_escape_string(trim($_POST['email']), $dbc);
$pass = mysql_real_escape_string(trim($_POST['pass']), $dbc);
if (empty($email)) {
$errors[] = 'Please enter your e-mail address.';
}
if (empty($pass)) {
$errors[] = 'Please enter your password.';
}
//if all fields filled out and everything is OK
if (empty($errors)) {
//check db for a match
$query = "SELECT user_id, first_name, user_level
FROM the rest of my sql here, blah blah blah";
$result = #mysql_query($query, $dbc)
OR trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error($dbc));
if (#mysql_num_rows($result) == 1) { //a match was made, OK to login
//register the retrieved values into $_SESSION
$_SESSION = mysql_fetch_array($result);
mysql_free_result($result);
mysql_close($dbc);
/*
setcookie('access'); //if "remember me" not checked, session cookie, expires when browser closes
//in FF you must close the tab before quitting/relaunching, otherwise cookie persists
//"remember me" checked?
if(isset($_POST['remember'])){ //expire in 1 hour (3600 = 60 seconds * 60 minutes)
setcookie('access', md5(uniqid(rand())), time()+60); //EXPIRES IN ONE MINUTE FOR TESTING
}
*/
echo '<font color="red">cookie:</font> ' . print_r($_COOKIE) . '<br><br>';
echo '<font color="red">session id:</font> ' . session_id() . '<br>';
echo '<font color="red">session first name:</font> ' . $_SESSION['first_name'] . '<br>';
echo '<font color="red">session user id:</font> ' . $_SESSION['user_id'] . '<br>';
echo '<font color="red">session user level:</font> ' . $_SESSION['user_level'] . '<br><br>';
ob_end_clean();
session_write_close();
$url = BASE_URL . 'loggedin_test2.php';
header("Location: $url");
exit();
} else {
//wrong username/password combo
echo '<div id="errors"><span>Either the e-mail address or password entered is incorrect or you have not activated your account. Please try again.</span></div>';
}
//clear $_POST so the form isn't sticky
$_POST = array();
} else {
//report the errors
echo '<div id="errors"><span>The following error(s) occurred:</span>';
echo '<ul>';
foreach($errors as $error) {
echo "<li>$error</li>";
}
echo '</ul></div>';
}
} // end isset($_POST['login'])
if I comment out the header redirect on the login page, I can echo out the $_SESSION variables with the right info from the DB. Once redirected to the login page, however, they're gone/unset.
Anyone have any ideas? I've spent nearly all day on this and can't say I'm any closer to figuring it out.
BTW, I recently made 2 simple test pages, one started a session, set some variables on it, had a form submit which redirected to a second page which did nothing but read/output the session vars. It all seems to work fine, I'm just having issues with something I'm doing in my main app.
I don't see a session_start() in your login script. If you aren't starting the session I don't think php will save any data you place in the $_SESSION array. Also to be safe I'd explicitly place variables into the $_SESSION array instead of just overwriting the whole thing with $_SESSION = mysql_fetch_array($result);.
Try doing a
session_regenerate_id(true);
before the
session_write_close();
Also. The best way IMO to do a login script is this:
Let the login logic be handled within the mainpage the user is trying to access.
If the user is not authenticated, he is thrown back to the login page
If the user is authenticated, he gets an $_SESSION["auth"] or something
Then when the user is browsing the main page or other pages that need auth, they just check if the $_SESSION["auth"] is set.
Then you wont have the trouble of session not saving just before a redirect
...may I add to the other answers, that session_start() sometimes fails or weird stuff occurs if not placed at the very first beginning of the script. In your header script, try:
Instead of
<?php
ob_start();
session_start();
Put
<?php
session_start();
ob_start();
I was having a similar problem when I discovered this:
http://www.w3schools.com/php/php_sessions.asp
You HAVE TO put the session_start(); before ANY html tags