Problem with saving session variables in PHP - php

I have an app that requires users to log in in order to use it and I use sessions in PHP in order to accomplish that. The first file index.ui.php includes this piece of code:
if ( isset( $_POST ) ) {
if ( $_POST['sent'] == 'sent' ) {
$msg = fx_login_user( $cn, $_POST['email'], $_POST['password'] );
if ( $msg == $_POST['email'] ) {
session_start();
$_SESSION['ss_user'] = $_POST['email'];
$job = fx_take_job( $cn, $_POST['email'] );
if ( $job == 'Tech' ) {
header("Location: index_tech.php");
exit;
} elseif ( $job == 'Admin' ) {
header("Location: index_admin.php");
exit;
} elseif ( $job == 'Root' ) {
header("Location: index_root.php");
exit;
}
}
}
}
And now, in ìndex_root.php (but also all the remaining index pages) I put a require("session.php") at the beginning in which I manage the access like this:
<?php
session_start();
if ( !isset( $_SESSION['ss_user'] ) ) {
header("Location: index.php");
die();
}
?>
In that same index_root.php I have a form that apart from the data saved in the session variable, gets the value of an entity and tries to save it into $_SESSION
Part of index_root.php
<?php
echo '<form class="form" id="form_info_user_root" method="POST" action="">';
echo '<input type="hidden" name="sent_user" value="user">';
echo '<input type="hidden" name="session" value="'.$_SESSION['ss_user'].'">';
echo '<input type="submit">';
?>
And form_root.php (which I include in index_root.php with another require() just before the one for session.php)
if ( isset( $_POST ) ) {
if ( $_POST['sent_user'] == 'user' ) {
session_start();
$_SESSION['ss_user'] = $_POST['session'];
$_SESSION['entity_info'] = substr( $_SERVER["REQUEST_URI"],
strrpos($_SERVER["REQUEST_URI"], "=" ) + 1 );
header("Location: info_user.php");
}
}
And now, in info_user.php, I also have at the beginning require("session.php") for the session management, but the two variables saved previously (which I both need for some logic in that page) get lost somehow and therefore, I get kicked out to index.php.
I did some logging to know when do I lose the variables (or maybe the session itself), and the ID of the session is the same in every page (as it should be, I guess) so it doesn't get finished, the variables are (as it looks like) properly saved in form_root.php, but they disappear once I enter to 'info_user.php'.
What can I do to maintain those variables or manage the session and its variables in a better way so that I can jump between pages without problems like this one?
Edit 1:
I've change the code a bit. I've now just put session_start() at the beginning of index_root.php and info_user.php and I have deleted that part in session.php and in form_root.php. The code becomes:
form_root.php
<?php
if ( isset( $_POST ) ) {
if ( $_POST['sent_user'] == 'user' ) {
$_SESSION['entidad_info'] = substr( $_SERVER["REQUEST_URI"],
strrpos($_SERVER["REQUEST_URI"], "=" ) + 1 );
header("Location: info_usuarios.php");
}
}
?>
Now I don't send the ss_user session variable via form and save it again, I just include another variable. However, by doing these changes, now in form_root.php I lose the ss_user, so I can't reach info_user.php because I am redirected to index.php. The variables still remain lost when I change between pages.

In the end I've been able to save the variables between form_root.php and info_user.php just by adding exit; after the header() function in the form file.
The code would stay like this:
if ( $_POST['sent_user'] == 'user' ) {
session_start();
$_SESSION['ss_user'] = $_POST['session'];
$_SESSION['entity_info'] = substr( $_SERVER["REQUEST_URI"],
strrpos($_SERVER["REQUEST_URI"], "=" ) + 1 );
header("Location: info_user.php");
exit;
}
This approach solves the specific problem, but I am forced to send the session data via form because I cannot access it from form_root.php's $_SESSION variable, so I've re-written that part of the code I previously had. However, this is just a partial solution, therefore, I am looking for a complete one yet.

Related

Session seems to disappear after header redirect

I have four pages so far:
index.php
login.php
setsessionconfig.php
account.php
The background:
When I click the login w/ facebook button from the index it takes me to login.php which if the user is already registered with the site it doesn't go through the facebook website it just continues. Login.php pulls the neccessary information for the session then header redirects to setsessionconfig.php which has the code below:
login.php has a 5 second delay for loading visual then redirects to ...
header( "refresh:5;url=".URLBASE."/setsessionconfig.php?uid=".$uid."&email=".$email );
setsessionconfig.php
$uid = isset($_GET['uid']) ? $_GET['uid'] : "";
$email = isset($_GET['email']) ? $_GET['email'] : "";
if( $uid != "" && $email != "") {
session_start();
$_SESSION[SESSION_UID] = $uid;
$_SESSION[SESSION_EMAIL] = $email;
$_SESSION[SESSION_IS_LOGGEDIN] = 1;
header("Location: account");
}
The Problem
When setsessionconfig.php redirects to account.php it checks to see if the users is logged in via the SESSION_UID global variable then displays the user information OR it displays the "you are not logged in" text. No matter what I do I think the header redirect to account.php is destroying session variables.
I even checked to see if the session was available with the following code in account.php.
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
if ( is_session_started() === FALSE )
echo "<script>console.log('FALSE');</script>";
else
echo "<script>console.log('TRUE - ".session_id()."');</script>";
Unfortunately that part actually returns the TRUE and the session ID... So I am sort of stuck because I have never had this issue with sessions before...
try using exit(); after the header
Since the function is_session_started, returned TRUE and also returned the session ID, obviously the session ID is passed properly.
I hope the account.php code looks something like this
<?php
session_start();
if (! empty($_SESSION['SESSION_UID']))
{
?>
your code here
<?php
}
else
{
echo 'You are not logged in.';
}
?>
Edit :
Try
$_SESSION['SESSION_UID'] = $uid;
$_SESSION['SESSION_EMAIL'] = $email;
$_SESSION['SESSION_IS_LOGGEDIN'] = 1;

Session Won't Start

In my login php page, after I check if the user's info is saved in the database, I set a session:
$_SESSION['username'] = $user;
if (isset($_SESSION['username'])) {
header( 'Location: index.php' );
}
and put session_start(); on this page at the tippy top.
Then it redirects me to index.php, telling me that the session has been set. On this page, I put session_start(); at the top but in the login area, I type:
<?php if (!isset($_SESSION['username'])) { echo $_SESSION['username'];?><li class="cat_0" id="login_btn_1">Login / SignUp</li>
<?php }
else {?>
<span id="login_show"><?php echo $_SESSION['username']; ?><a href="/account/logout.php?logout=1" id="logout_btn">LOGOUT</a></span>
<?php }?>
but every time, even if I reload, it shows the result for the !isset(), so that is telling em the session variable is not set. I check in my chrome cookies settings and it shows that PHPSESSID is set each time I test the Login. Can anyone explain why my session is not starting or what the problem is?
This is probably due to a simple race condition between your script and your session handling.
$_SESSION is a superglobal which has a specific way of working.
You are actually trying to access a superglobal variable which still only exists in the buffer of the session handler. If you want to access the session variable, you need to write the buffered data to the session by calling session_write_close() first:
$_SESSION['username'] = $user;
session_write_close(); // remember, you can no longer write to the sessions any more
if (isset($_SESSION['username'])) {
header( 'Location: index.php' );
exit; // just for safety
}
On the login page
-----------------
session_start();
if( !isset( $_SESSION['usename'] ) && isset( $user ) ) $_SESSION['username'] = $user;
if( isset( $_SESSION['username'] ) ) header( 'Location: index.php' );
On the index page
-----------------
if ( isset( $_SESSION['username'] ) ) {
echo '<span id="login_show">
'.$_SESSION['username'].'
LOGOUT
</span>';
} else {
echo "
<a href='/login.php'>
<li class='cat_0' id='login_btn_1'>Login / SignUp</li>
</a>";
}
There was an error in the html - there were two closing a tags together and quite often badly formed html can do all sorts of weird things to the display of the page.

php - Check Session strange beahviour

EDIT: Just wanted to add that by not having
exit();
As pointed by zerkms and user1578653 makes this code useless and probably dangerous, it should not be used.
Im writing a small cms and checking to see if the user is logged in trough sessions. Every page in my backoffice has a:
require('includes/security.php');
with the following code
<?php
session_start();
session_regenerate_id();
if (!isset($_SESSION["user_logged"]) or !isset($_SESSION["ip"]) )
{
session_destroy();
unset($_SESSION['user_logged']);
unset($_SESSION['ip']);
unset ( $_SESSION );
header("location: index.php");
}
if ($_SESSION["ip"] != $_SERVER['REMOTE_ADDR'])
{
session_destroy();
unset($_SESSION['user_logged']);
unset($_SESSION['ip']);
unset ( $_SESSION );
header("location: index.php");
}
if ($_SESSION["user_logged"] != "yes")
{
session_destroy();
unset($_SESSION['user_logged']);
unset($_SESSION['ip']);
unset ( $_SESSION );
header("location: index.php");
}
?>
If I try to acess any page directly it works as intended and redirects me to index.php except for a single page.
This page simple takes in data from a POST and updates/deletes the images/data in the Database.
The only difference I can think about is that this page doesn't have any html, and its on the same folder as every other.
But when I try to access it directly instead of redirecting me it trows:
Notice: Undefined variable: _SESSION
Warning: session_destroy() [<a href='function.session-destroy'>function.session-destroy</a>]: Trying to destroy uninitialized session
This page starts exactly like this:
<?php
require('includes/security.php');
// Engine - Update and Delete Images
What could be causing this?
Your code is most likely trying to destroy the session multiple times (once in each 'if'). You're also doing the exact same thing in each 'if' - try changing the code in security.php to:
<?php
session_start();
session_regenerate_id();
if(
!isset($_SESSION["user_logged"]) ||
!isset($_SESSION["ip"]) ||
$_SESSION["ip"] != $_SERVER['REMOTE_ADDR'] ||
$_SESSION["user_logged"] != "yes"
) {
session_destroy();
unset($_SESSION['user_logged']);
unset($_SESSION['ip']);
unset ( $_SESSION );
header("location: index.php");
exit();
}
?>

PHP Session & Login

I have a login and session creation script for a cms. It checks an admin file for correct details otherwise does a SQL query for user details. A session variable is set depending on which is successful then the according page loaded.
The script works on PHP 5.2 but I've been trying to rewrite the code to fix deprecated functions for PHP 5.4, register_globals and $http_session_vars in particular. The problem I think I am getting is that the variable ($s_Vers) is not being set properly as it's utilising an array.
To get around register_globals:
$aPwd = $_REQUEST['aPwd'];
$aLogin = $_REQUEST['aLogin'];
$lname = $_REQUEST['lname'];
$pswd = $_REQUEST['pswd'];
This seems to be working fine.
For $HTTP_SESSION_VARS I've replaced all instances with $_SESSION. I'm going to assume it's not that simple. An extract of the if statement that should set $s_vers for the admin.
if ( $lname === $aLogin
&& (( $aPwd && md5($pswd) === $aPswd )
|| (!$aPswd && $name === $pswd )) )
{
$s_Vers = $_SESSION["s_Vers"] = 0;
$s_aid = $_SESSION["s_uid"] = 0;
}
After this there is an else statement to run an SQL query for the user login details.
Then there is this:
else $wrong = true;
}
if( isset($_SESSION["s_Vers"]) && !#$wrong )
{
include "setup.php";
if( $s_Vers == 0 )
header("Location: adminpage.php");
else
header("Location: userpage.php");
exit();
}
Is there anything in the above that is glaringly wrong?
The session variables are being stored in the session array which looks like this:
session_start();
$session_array = array("username", "password", "s_uid", "s_Vers");
So what happens when I enter the admin details is that I see it direct to the adminpage.php as it should then it logs me out. I guess due to this:
if ( (!IsSet($curmode) && !$username) || isset($logout)
|| $s_Vers != $_SESSION["s_Vers"]
|| $s_uid != $_SESSION_["s_uid"]
)
{
$username = "";
$password = "";
$curmode = 0;
session_destroy();
// echo "Here";
// exit();
// Header("Location: http://".$g_AfterLogoutURL);
?>
<HTML>
<HEAD>
<TITLE>Not Authorised</TITLE>
<meta http-equiv="refresh" content="1;url=login.php">
</HEAD>
<SCRIPT language="javascript">
parent.location="login.php";
</SCRIPT>
<BODY>
</BODY>
</HTML>
<?
exit();
}
s_Vers is being set as global in two functions that are in a required file, but not executed until the adminpage is loaded.
There's other parts to the script with requires and variable declarations but not related to the session or login sequence.
Anyone know where I'm going wrong, or can provide a solution?
Check $_SESSION["s_Vers"] using var_dump();, bec. for
$s_Vers = $_SESSION["s_Vers"] = 0;
variables should be of one and the same type, otherwise = operator will not take place.
In your case it should be (int), bec. last item (which is 0) is of (int) type.

PHP Redirect, Keep POSTs

I have an html page with a checkbox form. The form has its action pointing to a PHP script. The PHP script collects the POST variables just fine but obviously a blank screen displays because it goes to www.example/script.php once executed.
How I do get PHP to go to another URL for more form submission information while keeping those POSTs intact?
header() and metaredirect seem to overrule everything and not collect the data... How do I collect that data into POSTs and then automatically go to another html page for another form with a PHP script attached as its action?
Thanks and sorry if I worded this in a confusing manner.
You could either store the $_POST variables in $_SESSION and then submit them when the final part of the form is completed, or you could have the intermediary page store these values as hidden inputs and submit them to the final page.
I've found that this code works almost all the time (except in some cases where you want to forward using custom post data and the client doesn't support javascript).
This is done by abusing the 307 Temporary Redirect which seems to forward POST data, or by creating a self submitting javascript form.
This is a hack though, only use it if you MUST forward the POST data.
<?php
function redirectNowWithPost( $url, array $post_array = NULL )
{
if( is_null( $post_array ) ) { //we want to forward our $_POST fields
header( "Location: $url", TRUE, 307 );
} elseif( ! $post_array ) { //we don't have any fields to forward
header( "Location: $url", TRUE );
} else { //we have some to forward let's fake a custom post w/ javascript
?>
<form action="<?php echo htmlspecialchars( $url ); ?>" method="post">
<script type="text/javascript">
//this is a hack so that the submit function doesn't get overridden by a field called "submit"
document.forms[0].___submit___ = document.forms[0].submit;
</script>
<?php print createHiddenFields( $post_array ); ?>
</form>
<script type="text/javascript">
document.forms[0].___submit___();
</script>
<?php
}
exit();
}
function createHiddenFields( $value, $name = NULL )
{
$output = "";
if( is_array( $value ) ) {
foreach( $value as $key => $value ) {
$output .= createHiddenFields( $value, is_null( $name ) ? $key : $name."[$key]" );
}
} else {
$output .= sprintf("<input type=\"hidden\" name=\"%s\" value=\"%s\" />",
htmlspecialchars( stripslashes( $name ) ),
htmlspecialchars( stripslashes( $value ) )
);
}
return $output;
}

Categories