PHP Session_start is hanging - php

Kind of a weird issue, ok here is my setup...
domain.com calls reads from an Iframe on sub.domain.com
sub.domain.com makes an ajax call to sub.domain.com/call.php
sub.domain.com returns ajax call to domain.com
AKA long-polling
Now, everything works perfectly when there is no session data (I close the browser and restart the page). However, once I reload the page and their is session data, call.php does a start_session() and hangs there.
I have tried almost everything and can't figure this out. I've tried destroying the session, unsetting all the session variables, modifying some ini settings, and nothing has worked.
Here is the code of call.php where the session data is...
session_start();
$sql = ("SELECT userid FROM status WHERE typing = '".mysql_real_escape_string($userid)."'");
$result = mysql_query($sql);
if ($result && mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$typing_id = $row['userid'];
if (!empty($typing_id)) {
if (isset($_SESSION['typing2'])) {
unset($_SESSION['typing2']);
}
} else {
$typing_id = "-1";
}
} else {
$typing_id = "-1";
if (isset($_SESSION['typing'])) {
unset($_SESSION['typing']);
}
}
if ($_SESSION['typing'] != $typing_id && !isset($_SESSION['typing2']) || $initialize == "1") {
$typing = array('typing_id' => $typing_id);
}
if ($typing_id == "-1") {
$_SESSION['typing2'] = "-1";
} else {
$_SESSION['typing'] = $typing_id;
}
Does anyone have any ideas? I was thinking it might have to do with the domain but I'm not sure.
Thanks!

I actually found out (after hours and hours of debugging and research) that the problem is being caused because the PHP session locks up. Then, when the new page loads, it won't work until the old session times out. A session_write_close() will fix it.

default session storage in php is cookie based. if you are using that you must set domain for your session cookie in php.ini
http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain

Related

PHP: Remember Me, Stay logged in doesn't work

In my PHP project, I want to add a user remember me checkbox so that everybody can choose to stay logged in:
Until now I do my normal log in like:
public function loginUser($psMail, $psPwd, $pnRememberMe = 0) {
// Check credentials and so on
// If mail and password matches
if(CREDENTIALS OKAY) {
$_SESSION["username"] = "foo";
$lnExpire = time() + 3600 * 24 * 60;
setcookie("remember", base64_encode(USERID), $lnExpire);
setcookie("rememberToken", md5(SOMESTUFF), $lnExpire);
}
}
When I log in, I can see the created cookie variables with:
print_r($_COOKIE);
Now I try to leave the site with my logout function:
// Unset the session variables
$_SESSION = array();
// Destroy the session.
session_destroy();
But now, when I am at the landing page, there are also my cookies gone?
Could this be because of my session site settings?
ini_set("session.use_only_cookies", "1");
ini_set("session.use_trans_sid", "0");
php function setcookie has fourth argument path, from documentation "The path on the server in which the cookie will be available on". By default it set path to actual your directory. Try set "/" Then it will be available for all domain. http://php.net/manual/en/function.setcookie.php
Try this code hope it will work for you
if(count($_POST>0) && isset($_POST['checkbox']))
{
setcookie('name',$_POST['uname'],time()+3600);
setcookie('password',$_POST['pw'],time()+3600);
}
elseif(count($_POST)>0)
{
setcookie('name','',time()-3600);
setcookie('password','',time()-3600);
}
if(count($_POST)>0 && $_POST['uname']!="" && $_POST['password']!="")
{
if(isset($_COOKIE['name']) && isset($_COOKIE['password']))
{
echo $_COOKIE['name'];
echo $_COOKIE['password'];
}
your login detail code here.....

Infinite loop php redirect based on cookie

I'm currenting busy coding a registration page. The page has three steps and every step has its own cookie value. What I'd like to do is checking for the cookies value and transfer the user to the correct page upon visiting the website
Example:
if the value of $_COOKIE['step'] is 'step_two' it should redirect to: www.domain.com/register.php?step=your_details. If the cookie's not set, it should not redirect and stay on the register.php page.
The redirecting is working 'fine', but it gets into an infinite loop. I really cant think clear anymore as I've been awake for almost 24h now. Therefor I would appreciate it if anyone could push me into the right directions.
Piece of code:
$cookie_value = 'step_2';
setcookie("step",$cookie_value, time()+3600*24);
$cookie_not_set = true;
$cookie_step_two = false;
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
$cookie_not_set = false;
$cookie_step_two = true;
header('Location: ?step=your_details');
exit();
}
} else {
$cookie_not_set = true;
}
Thank you.
Nowhere are you actually setting your cookie value, so it won't change. That's why you have an infinite loop.
$_GET and $_COOKIE have nothing to do with each other. It looks like you want:
if ($_GET['step'] === 'your_details')`
...which would be better than using a cookie anyway.
You are going to constantly enter your if condition as there is no other manipulations going on to your cookie data.
if your cookie is set to "step_2" you will enter the loop. No changes are in place, so on the refresh to the page. You will re-enter the step_2 condition and be into a redirect.
I'm also assuming that you understand that your $_GET & $_COOKIE requests are completely different. If not, see #Brads answer
A solution to stop this infinite loop would be:
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
$cookie_not_set = false;
$cookie_step_two = true;
$_COOKIE['step'] = 'step_3';
header('Location: ?step=your_details');
exit();
}
But also take note, your true/false validations/changes are local changes and will not be absolute on page refresh
I believe your issue is the redirect is not changing your cookie, so you need to look at the GET var you a re passing if the cookie is set to step_2 thus;
$cookie_not_set = true;
$cookie_step_two = false;
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
if( !empty($_GET['step']) && $_GET['step'] == 'your_details' )
{
... you have redirected and now can continue ...
}
else
{
// redirect and set the get var to signal to this script.
$cookie_not_set = false;
$cookie_step_two = true;
header('Location: ?step=your_details');
exit();
}
}
} else {
$cookie_not_set = true;
}

PHP session variables getting lost after a header redirect

I cannot figure this out. Sometimes after the redirect (see code below), the session variables are lost. Any ideas?
Note the script is initially called with ?p=1&u=2&k=3.
As you can see, the script redirects to itself. The session variables something are lost after the redirect.
<?php
session_start();
if ((isset($_SESSION['p'])) and ($_SESSION['p'] != "")) {
// do something
} else {
$_SESSION['p'] = $_GET['p'];
$_SESSION['w'] = $_SERVER["HTTP_HOST"];
$_SESSION['u'] = $_GET['u'];
$_SESSION['k'] = $_GET['k'];
header("Location: http://".$_SESSION['w'].$_SERVER['PHP_SELF']."");
exit();
}
?>
Cheers
Copied and pasted your code and it works just fine for me.
Do you maybe have some spaces or whatever before your <?php-tag?
I am not sure why it happens.
Probably you have some misconfiguration on your php.ini file.
Or you don't have the right session.save_path or permissions to write there.
But if the problem persists, try this way:
<?php
session_start();
if (!$_SESSION['p']) {
$_SESSION['p'] = $_GET['p'];
$_SESSION['w'] = $_SERVER["HTTP_HOST"];
$_SESSION['u'] = $_GET['u'];
$_SESSION['k'] = $_GET['k'];
}
//code comes here
?>
In my opinion, this is the way things should be done.

Not able to maintain values in session

Not able to maintain values in session at the client side(Member login).
In the code below, we had stored client id in a session variable. But we can’t access that in myprofile.php. So after login, we can’t maintain myprofile page.
What could be the error?
case "LOGIN":
{
$username = $_REQUEST['a0'];
$password = md5($_REQUEST['a1']);
$table_name = "coco_members";
$count = $fn->returnColumn($table_name,"count(*) as val","member_uname='$username' and member_pwd='$password' and member_active='1'");
if($count>0)
{
$result = $fn->returnColumn($table_name,"member_id","member_uname='$username' and member_pwd='$password' and member_active='1'");
}
else
{
$result ="";
}
if($result!="")
{
$_SESSION['CID'] = $result;
echo $_SESSION['CID'];
}
else
{
$_SESSION['CID']="";
echo "NOK";
}
break;
}
case "GETPOSTS":
{
$page = $_REQUEST['page'];
$activeid = $_REQUEST['id'];
$count = $_REQUEST['count'];
include("includes/client.php");
echo getPosts($page,$activeid,$count);
break;`
I also had some problems with sessions at some servers. In XAMP it would work prefect but when transferred on server it would not recognize session. Finally I find solution for this, by trails and errors. By creating session.php file and including it at the top of all files that needed session. Just write session_start(); in session.php and that is all.
Dunno if this will help you but it helped me while working on few project that had servers who wouldn't do what they needed to.
EDIT: In 90% percent of my cases, that had this problem, where on free servers so if your working on free server this might fix it.

Sessions are going crazy. Only Mozilla is able to process

PROBLEM
I've got an admin panel. Currently only Mozilla is able to process log ins. Browsers like Chrome, IE, Opera won't even show any message carried through sessions thus no one is able to log in any browser but Mozilla.
SOME INFORMATION
I'm using PHP 5.3.6 on my server, PHP 5.3.5 on my local
computer.
My code is Object Oriented.
ini_set("session.use_only_cookies", 1); and
ini_set('session.cookie_secure', 1); are used in construction method
of my session class.
This website on SLL
Login process: First I gather all information from form, validate and gather data. After validation if everything is right, I send this data to login method in my session class.
public function login ($user) {
global $siteSettings;
if ($user) {
$this->id = $_SESSION['id'] = $user->id;
$this->username = $_SESSION['username'] = $user->username;
$this->fullName = $_SESSION['fullName'] = $user->fullName;
$this->group_id = $_SESSION['group_id'] = $user->group_id;
$this->groupName = $_SESSION['groupName'] = $user->groupName;
$this->lastLogin = $_SESSION['lastLogin'] = $user->lastLogin;
$this->isAdmin = $_SESSION['isAdmin'] = ($user->admin == 1) ? true : false;
$this->isAgent = $_SESSION['isAgent'] = ($user->agent == 1) ? true : false;
self::$language = $_SESSION['language'] = ($user->language != "" || $user->language != NULL) ? $user->language : self::$language;
if ($user->language != "" || $user->language != NULL) {
$_SESSION['language'] = $user->language;
}else {
if (!defined(DEFAULT_LANGUAGE)) {
$browserLang = "|".$_SERVER["HTTP_ACCEPT_LANGUAGE"];
$browserLang = getStringBetween($browserLang, "|","-", FALSE);
if (!file_exists(LANGUAGES.$browserLang.".php")) $browserLang = FALSE;
}
$_SESSION['language'] = ($browserLang) ? $browserLang : DEFAULT_LANGUAGE;
}
# When 2 Update session_id
$date = new DateTime("now");
$UpdateTime = $siteSettings->session->timeOut * 60;
$date->add(new DateInterval("PT".$UpdateTime."S"));
$_SESSION['SIDUpdateTime'] = $date->format("Y-m-d G:i:s");
# UPDATE LAST LOGIN & ADD SESSION ID
# Clear Fields
members::clearFields();
members::$fields['id'] = $_SESSION['id'];
members::$fields['lastLogin'] = date("Y.m.d G:i:s");
members::$fields['lastLoginIP'] = $_SERVER['REMOTE_ADDR'];
# GET THE SALT
$saltInfo = members::getData("id", "salt", members::$fields['id']);
# SETTING SESSION ID ENCRYPTION
crypt::setKey($saltInfo->salt);
members::$fields['sessionID'] = crypt::encode(session_id());
members::$fields['sessionIP'] = $_SERVER['REMOTE_ADDR'];
members::$fields['sessionAgent'] = $_SERVER['HTTP_USER_AGENT'];
members::save();
$this->loggedIn = true;
var_dump($_SESSION);
}
}
When I dumb the data I can see $_SESSION got some values.
Just to test it, I stopped the script where after var_dump($_SESSION); (added die();) I created test.php file and tried this;
<?php
ob_start();
session_start();
echo '<pre>';
var_dump($_SESSION);
echo '<pre>';
ob_end_flush();
?>
Output is array(0) {}
But when I try exactly the same thing with Mozilla, output of test.php is the way it should be (matching with login method's result in my session class).
I have tried from my local computer and I don't experience the same
problem.
I disabled all java script and jquery codes from the page just to
have no 'maybe' in my mind.
After dumping the data, script is stopped. That's why $_SESSION variable shouldn't change. For some reason when it is on the server only Mozilla is able to show expected result while other browsers shows NULL.
At this point I really don't know what to think of about this problem to try to solve it. All I can think of is, this problem is possibly related to server configuration. But then, PHP is server side programming. PHP shouldn't display different behavior for browsers like Jquery, CSS, HTML...
I'm sorry, I can't provide admin panel link. Considering this is an active admin panel. If necessary I could install it on another domain to let you try but I believe the information I gave above explains everything.
Thank you for your help in advance.
I had a similar problem... just enable the cookies.. so that after login the code to set the sessions will be executed and the sessions will be set. may be the sessions r not able to set...
also check this http://php.net/manual/en/function.session-cache-limiter.php
If something large doesn't work, trim it down, test & debug, and build up from there.
Does this work? (Run it twice).
<?php
session_start();
echo "Session ID: " . session_id() . "<br/>\n";
if (!isset($_SESSION['test']))
{
$_SESSION['test'] = "foobar";
echo "Setting session variable: ";
echo $_SESSION['test'];
}
else
{
echo "Restoring session variable: ";
echo $_SESSION['test'];
}
If this works in all browsers, it's got something to do with your code. An empty session might have something to do with a cookie that can't be written, for example. Also set error reporting to E_ALL | E_STRICT, so you'll see everything that goes wrong.
It turns out Mozilla FireFox is able to process some data but other browsers I tried with are not and therefore they reset the whole session with each page load.
I had no problem with my local computer but on the server I had sessions problem. I don't know why session_set_cookie_params(); and setcookie(); didn't work on the server so I had to code longer version;
private static function sessionLifeTime() {
global $siteSettings;
# HOW LONG WE WANT SESSIONS
$lifeTime = intval($siteSettings->session->timeOut) * 60;
if (isset($_SESSION['id']) && isset($_SESSION['lastActivity']) && (time() - $_SESSION['lastActivity'] > $lifeTime) ) {
// SEND INFORMATION TO USER
self::logout();
}
$_SESSION['lastActivity'] = time();
}
Replacing my method with the code above solved the problem.
Thank you all for your time, concern and interest.

Categories