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'];
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?
So this is how my login process works:
authenticate.php
sessionStart();
if (isset($_SESSION) && !empty($_SESSION['LOCATION'])) {
$location = $_SESSION['LOCATION'];
unset($_SESSION['LOCATION']);
} else {
$location = '//' . $_SERVER['SERVER_NAME'];
}
session_write_close();
sessionStart();
$userIsOnline = isset($_SESSION['ID']);
session_write_close();
sessionStart();
if (!$userIsOnline) {
// Get the user from the database
// Validate the user's password
$_SESSION['ID'] = $user->id;
$_SESSION['UN'] = $user->un;
// ... more information
}
session_write_close();
header($location);
exit();
The contents of the sessionStart function:
if (session_id() == '') {
session_name('MyWebsite');
session_set_cookie_params(86400, '/', $_SERVER['SERVER_NAME'], true, true);
session_start();
$_SESSION['LAST_ACTIVITY'] = time();
$_SESSION['CREATED'] = time();
}
Then on the top of every page on my website:
sessionStart();
print_r($_SESSION);
$_SESSION['LOCATION'] = $_SERVER['REQUEST_URI'];
session_write_close();
Prints an empty array. So for some reason, it is wiping my session array during the redirect? Anyone have any ideas?
Also, the values of CREATED and LAST_ACTIVITY are from this question.
If it is not the issue that HTTPS is not used, but the session cookie is set to Secure then my other thought is to change
if (session_id() == '') {
session_name('MyWebsite');
session_set_cookie_params(86400, '/', $_SERVER['SERVER_NAME'], true, true);
to
if (session_name('MyWebsite') != 'MyWebsite') {
session_set_cookie_params(86400, '/', $_SERVER['SERVER_NAME'], true, true);
I wonder if it is giving you a Session ID under a different name, which is why print_r($_SESSION); is coming up empty. If not, I'm out of ideas!
I'm working on a site that has a My Account section that the user has to login to. I'm storing the users basic information in the session after they have logged in.
I'm having no problem in Chrome or Firefox with this. However, in IE 8 I login, and it redirects to the main back office page. It loads, but right after the session is cleared. I tested this by printing the session after session_start() then again at the end of the page. All the information is there when the page loads. If I open a separate page and print out the session right after, it's already cleared. Again, only in IE does this happen.
Is there something I'm missing here?
CODE
This is the code on all of the Account pages.
<?php
require_once('inc_session.php');
require_once('bo_session_check.php');
?>
On the page logged into (backoffice.php), the only other time the session is used, is when it is read to determine what kind of account the person has logged into, for example:
<?php if($_SESSION['user_type']=='member'){?>
Code for inc_session.php
<?php
if(!isset($_SESSION['is_mobile'])){
$mobile_browser = '0';
if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
$mobile_browser++;
}
if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
$mobile_browser++;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
//echo $_SERVER['HTTP_USER_AGENT'];
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda ','xda-');
if (in_array($mobile_ua,$mobile_agents)) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini') > 0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'ipad') > 0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0) {
$mobile_browser = 0;
}
if ($mobile_browser > 0) {
$_SESSION['is_mobile']='yes';
}
else {
$_SESSION['is_mobile']='no';
}
}
/* TURN MOBILE SITE OFF */
//$_SESSION['is_mobile']='no';
$page=strtok($_SERVER["REQUEST_URI"],'?');
if(substr($page, 0, 3)!="/m/" && $_SESSION['is_mobile']=='yes' && substr($page,-3) =='php'){
if( isset($_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] != 'off' ){
$heading='https://';
}else{
$heading='http://';
}
header("Location: " . $heading . $_SERVER["SERVER_NAME"] . "/m" . $_SERVER["REQUEST_URI"]);
exit();
}
$page=substr($page, strrpos($page, '/', -1));
$ssl_pages=array('/backoffice.php', '/login.php', '/login-partner.php', '/checkout.php', '/checkout_member.php', '/membership.php', '/partner.php');
if(in_array($page, $ssl_pages) || substr($page, 0, 3)=='/bo'){
if($_SERVER[HTTP_HOST]!='domain.com'){
header("Location: https://domain.com" . $_SERVER["REQUEST_URI"]);
}elseif($_SERVER["HTTPS"] != "on") {
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]);
exit();
}
}else{
if($_SERVER["HTTPS"] == "on"){
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]);
exit();
}
}
ini_set("session.cookie_domain", "domain.com");
session_start();
?>
This is bo_session_check.php
if(isset($_SESSION['agreed']) && $_SESSION['agreed']!="yes" && $_SESSION['admin']!="yes"){
/*
DEPRECIATED
header("location: bo_terms.php");
exit();
*/
$_SESSION['agreed']="yes";
}elseif(isset($_SESSION['user_id']) && $_SESSION['user_id']!=""){
/*ALL GOOD*/
}else{
/*YOU GOTTA GO*/
header("location: login.php");
exit();
}
?>
Here is the PHP Session Info
Since $_SESSION is handled server-side -- this is going to mean that cookies are disabled in IE8 -
You have session.use_only_cookies = On, which is fine, but just be aware that anyone with cookies turned off will fail to load your site properly.
However, this is not what is causing the issue.
From other StackOverflow answer:
Try putting [PHP code below] prior to starting the session - this would ensure that the session cookie will not expire until the browser is closed.
session_set_cookie_params(0);
Hope this helps solve your problem. Worst case scenario, pass the SESSION ID (SID) through the URLs in between page loads and redirects. Refer to this page in the PHP Manual on passing Session IDs. You would have to do this through the Location: http://URL that you have.
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')