Symfony2 not saving sessions properly - php

I'm having a problem with Symfony creating a new session on each page load, rather than carrying data across requests. The auto_start in the session section in the config.yml is set to false, and regular php sessions work fine. It's only when running in symfony that I get the problem.
For example, I created the test action:
public function sessionTestAction()
{
$s_Response = '<html><head></head><body><p>Foo</p></body></html>'; //Initialize response and headers
$a_Headers = array();
$i_StatusCode = 200;
$oSession = $this->get('session');
var_dump($oSession->all());
if(!$oSession->has('Test'))
{
$oSession->set('Test', 'Bar');
}
$oSession->save();
return new Response($s_Response, $i_StatusCode, $a_Headers);
}
The expected action is, that on the first page load, the var_dump will yield nothing, and that on any subsequent executions, it will contain Test=>Bar. However, it never gets that data across requests.
In addition, it creates a new session id for each request.
I am using Symfony v2.0.15, and PHP v5.4
Anyone have any ideas?
Edit:
I made some progress, I think. I made the following changes to the test action:
public function sessionTestAction()
{
//Initialize response and headers
$oRequest = $this->get('request');
$a_Headers = array();
if (isset($oRequest->headers->all()['cookie']))
{
$a_Headers['Set-Cookie'] = $oRequest->headers->all()['cookie'];
}
$i_StatusCode = 200;
$oSession = $oRequest->getSession();
$oSession->start();
$s_Response = print_r($oSession->all(), true);
if(!$oSession->has('Test'))
{
$oSession->set('Test', 'Bar');
}
$oSession->save();
$oResponse = new Response($s_Response, $i_StatusCode, $a_Headers);
return $this->render('Bundle:Default:index.html.twig', array('response' => $s_Response), $oResponse);
}
Where that twig file has just {{response|raw}}. It now holds the session for 2 out of 3 of the requests. However, on the third request, it's cleared.

Turned out the problem was, someone added a line to set a session cookie whenever the app.php was run, not knowing that symfony handled sessions itself, I guess. Problem solved.

I got this problem a couple times, its very annoying. So, let me describe possible solution.
Open dev environment - yourdomain.com/app_dev.php/ Try to refresh page a couple times. If you see session ID changed each time - it means that sessions are broken.
If you are using chrome (if not - you should, its the best for developers ;) ) - you can open developers tools (click F12).
Next, check Network tab, refresh page and locate your main request.
Check headers for your request - if should see "Cookie:PHPSESSID".
If you dont see - something wrong with cookies. In my case it was
framework:
session:
cookie_domain: mydomain.com

Related

Php session data is returning wrong value

I have an application that i built in php 7 with the code-igniter framework and my problem is with the session data , storing and retrieving session data works fine , but occasionally when two people log in at close intervals , the session data for the first user is also retrieved for the second user, searched through the site , saw something similar here (wrong data in PHP session) that suggested that it might be a caching issue (my site uses nginx for caching) , but no concrete solutions were suggested. Any suggestions or Ideas will be appreciated.
Edit : Here is the section of my login library for authentication
public function login_account($email,$password)
{
$db = "db";
$data = array("login_mail" => sha1($email));
$query_result = $this->CI->m_eauth->get_login_password($data,$db);
$hash_password ="";
foreach($query_result->result_array() as $value)
{
$hash_password = $value['hash_password'];
$site_name = $value['hash_name'];
$account_type = $value['account_type'];
$site_match_id = $value['site_match_id'];
$site_levels = $value['levels'];
$site_roles = $value['roles'];
}
if(password_verify($password, $hash_password)){
// Success!
$session_data = array(
"site_id"=>$site_match_id,
"site_email"=>$email,
"site_name"=>$site_name,
"site_avatar"=>md5($email).".jpg",
"site_type"=>$account_type,
"site_levels"=>$site_levels,
"site_roles"=>$site_roles
);
$this->CI->session->set_userdata($session_data);
return "successful";
}
else{
// Invalid credentials
return "unsuccessful";
}
}
Let me add that the login works fine and individual sessions work just fine. But every now and then the problem i described happens , and i'ts quite confusing as i don't know where to look.
There's no real way to sugar coat this, sessions aren't some magical part of PHP that you enable you to just call session_start() and go about your day. If your application is leaking sessions then you haven't secured it properly and you need to fix it.
Session security is a pretty big deal, given that a hijacked session basically gives an attacker total access to someone else's account.
I would recommend you read the official PHP session docs and also consider implementing the Nginx userid module as an additional measure for identifying users.

Laravel store session in cookie

I have a website where the front page contains a search form with several fields.
When the user performs a search, I make an ajax call to a function in a controller.
Basically, when the user clicks on the submit button, I send an ajax call via post to:
Route::post('/search', 'SearchController#general');
Then, in the SearchController class, in the function general, I store the values received in a session variable which is an object:
Session::get("search")->language = Input::get("language");
Session::get("search")->category = Input::get("category");
//I'm using examples, not the real variables names
After updating the session variable, in fact, right after the code snippet shown above, I create (or override) a cookie storing the session values:
Cookie::queue("mysite_search", json_encode(Session::get("search")));
And after that operation, I perform the search query and send the results, etc.
All that work fine, but I'm not getting back the values in the cookie. Let me explain myself.
As soon as the front page of my website is opened, I perform an action like this:
if (!Session::has("search")) {
//check for a cookie
$search = Cookie::get('mysite_search');
if($search) Session::put("search", json_decode($search));
else {
$search = new stdClass();
$search->language = "any";
$search->category = "any";
Session::put("search", $search);
}
}
That seems to be always failing if($search) is always returning false, and as a result, my session variable search has always its properties language and category populated with the value any. (Again: I'm using examples, not the real variables names).
So, I would like to know what is happening here and how I could achieve what I'm intending to do.
I tried to put Session::put("search", json_decode($search)); right after $search = Cookie::get('mysite_search'); removing all the if else block, and that throws an error (the ajax call returns an error) so the whole thing is failling at some point, when storing the object in the cookie or when retieving it.
Or could also be something else. I don't know. That's why I'm here. Thanks for reading such a long question.
Ok. This is what was going on.
The problem was this:
Cookie::queue("mysite_search", json_encode(Session::get("search")));
Before having it that way I had this:
Cookie::forever("mysite_search", json_encode(Session::get("search")));
But for some reason, that approach with forever wasn't creating any cookie, so I swichted to queue (this is Laravel 4.2). But queue needs a third parameter with the expiration time. So, what was really going on is that the cookie was being deleted after closing the browser (I also have the session.php in app/config folder set to 'lifetime' => 0 and 'expire_on_close' => true which is exactly what I want).
In simple words, I set the expiration time to forever (5 years) this way:
Cookie::queue("mysite_search", json_encode(Session::get("search")), 2592000);
And now it seems to be working fine after testing it.

Google API request every 30 seconds

I'm using Live Reporting Google APIs to retrieve active users and display the data inside a mobile application. On my application I'd like to make a HTTP request to a PHP script on my server which is supposed to return the result.
However I read on Google docs that it's better not to request data using APIs more often than 30 seconds.
I prefer not to use a heavy way such as a cron job that stores the value inside my database. So I'd like to know if there's a way to cache the content of my PHP scrpit na dmake it perform an API request only when the cache expires.
Is there any similar method to do that?
Another way could be implementing a very simple cache by yourself.
$googleApiRequestUrlWithParameter; //This is the full url of you request
$googleApiResponse = NULL; //This is the response by the API
//checking if the response is present in our cache
$cacheResponse = $datacache[$googleApiRequestUrlWithParameter];
if(isset($cacheResponse)) {
//check $cacheResponse[0] for find out the age of the cached data (30s or whatever you like
if(mktime() - $cacheResponse[0] < 30) {
//if the timing is good
$googleApiResponse = $cacheResponse[1];
} else {
//otherwise remove it from your "cache"
unset($datacache[$googleApiRequestUrlWithParameter]);
}
}
//if you do no have the response
if(!isset($googleApiResponse)) {
//make the call to google api and put the response in $googleApiResponse then
$datacache[] = array($googleApiRequestUrlWithParameter => array(mktime(), $googleApiResponse)
}
If you data are related to the user session, you could store $datacahe into $_SESSION
http://www.php.net/manual/it/reserved.variables.session.php
ortherwise define $datacache = array(); as a global variable.
There is a lot of way of caching things in PHP, the simple/historic way to manage cache in PHP is with APC http://www.php.net/manual/book.apc.php
Maybe I do not understard correctly your question.

login to php website using RCurl

I would like to access with R to the content of a php website
http://centralgreen.com.sg/login.php?login=9-1501&password=mypassword
I have passed an example of login + password in the url, but I don't know how to press the login button through the url.
I would like to use the R package RCurl if possible.
The form submits by post - you are using a get request at the moment by the looks of things, you need to use post.
My guess is that rcurl is based on curl - and I know curl can do this, so should be possible.
recently I've been having the same problem. In my case I solved it like this, using RCurl package (with a POST request).
In this code two requests are done one after the other. The fist one, is in order to gain a session cookie (start session in the server). The application I was calling expected the session to be started by the time it checked the login credentials (this won't happen if you send the form upfront). Otherwise some warning about not having cookie support was raised. This might be the case of the asker (though it was time ago)... or someone else's.
login <- function (xxxx_user, xxxx_pass) {
url_login <- 'http://centralgreen.com.sg/login.php'
curlhand <- getCurlHandle()
curlSetOpt(
.opts = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")),
cookiefile = "cookies.txt",
useragent = 'YOUR R-PACKAGE NAME',
followlocation = TRUE,
# might need this in case the server checks for the referer..
httpheader = "Referer: http://centralgreen.com.sg",
curl = curlhand)
# (1) first call to initializate session. you get the session cookie
getURL(url_login, curl = curlhand)
params<- list( login = xxxx_user, password = xxxx_pass )
# might need to add some other hidden form param in case there are..
# (2) second call, sends the form, along with a session cookie
html = postForm(url_login,
.params = params,
curl = curlhand,
style="POST")
# ... perform some grep logic with 'html' to find out weather you are connected
}
# you call the function...
login("yourusername", "yourpass")
The 'perform some grep logic' note takes care of the fact that since you are targeting a system not designed for this kind of programatical log in, it's not going to give you any nice hint on the result of the attempt ... so you might need to parse the raw html string you receive against some key sentences (eg: 'wrong username or password' ...)
hope it helps

CakePHP: Action runs twice, for no good reason

I have a strange problem with my cake (cake_1.2.0.7296-rc2).
My start()-action runs twice, under certain circumstances, even though only one request is made.
The triggers seem to be :
- loading an object like: $this->Questionnaire->read(null, $questionnaire_id);
- accessing $this-data
If I disable the call to loadAvertisement() from the start()-action, this does not happen.
If I disable the two calls inside loadAdvertisement():
$questionnaire = $this->Questionnaire->read(null, $questionnaire_id);
$question = $this->Questionnaire->Question->read(null, $question_id);
... then it doesn't happen either.
Why?
See my code below, the Controller is "questionnaires_controller".
function checkValidQuestionnaire($id)
{
$this->layout = 'questionnaire_frontend_layout';
if (!$id)
{
$id = $this->Session->read('Questionnaire.id');
}
if ($id)
{
$this->data = $this->Questionnaire->read(null, $id);
//echo "from ".$questionnaire['Questionnaire']['validFrom']." ".date("y.m.d");
//echo " - to ".$questionnaire['Questionnaire']['validTo']." ".date("y.m.d");
if ($this->data['Questionnaire']['isPublished'] != 1
//|| $this->data['Questionnaire']['validTo'] < date("y.m.d")
//|| $this->data['Questionnaire']['validTo'] < date("y.m.d")
)
{
$id = 0;
$this->flash(__('Ungültiges Quiz. Weiter zum Archiv...', true), array('action'=>'archive'));
}
}
else
{
$this->flash(__('Invalid Questionnaire', true), array('action'=>'intro'));
}
return $id;
}
function start($id = null) {
$this->log("start");
$id = $this->checkValidQuestionnaire($id);
//$questionnaire = $this->Questionnaire->read(null, $id);
$this->set('questionnaire', $this->data);
// reset flow-controlling session vars
$this->Session->write('Questionnaire',array('id' => $id));
$this->Session->write('Questionnaire'.$id.'currQuestion', null);
$this->Session->write('Questionnaire'.$id.'lastAnsweredQuestion', null);
$this->Session->write('Questionnaire'.$id.'correctAnswersNum', null);
$this->loadAdvertisement($id, 0);
$this->Session->write('Questionnaire'.$id.'previewMode', $this->params['named']['preview_mode']);
if (!$this->Session->read('Questionnaire'.$id.'previewMode'))
{
$questionnaire['Questionnaire']['participiantStartCount']++;
$this->Questionnaire->save($questionnaire);
}
}
function loadAdvertisement($questionnaire_id, $question_id)
{
//$questionnaire = array();
$questionnaire = $this->Questionnaire->read(null, $questionnaire_id);
//$question = array();
$question = $this->Questionnaire->Question->read(null, $question_id);
if (isset($question['Question']['advertisement_id']) && $question['Question']['advertisement_id'] > 0)
{
$this->set('advertisement', $this->Questionnaire->Question->Advertisement->read(null, $question['Question']['advertisement_id']));
}
else if (isset($questionnaire['Questionnaire']['advertisement_id']) && $questionnaire['Questionnaire']['advertisement_id'] > 0)
{
$this->set('advertisement', $this->Questionnaire->Question->Advertisement->read(null, $questionnaire['Questionnaire']['advertisement_id']));
}
}
I really don't understand this... it don't think it's meant to be this way.
Any help would be greatly appreciated! :)
Regards,
Stu
Check your layout for non-existent links, for example a misconfigured link to favicon.ico will cause the controller action to be triggered for a second time. Make sure favicon.ico points towards the webroot rather than the local directory, or else requests will be generated for /controller/action/favicon.ico rather than /favicon.ico - and thus trigger your action.
This can also happen with images, stylesheets and javascript includes.
To counter check the $id is an int, then check to ensure $id exists as a primary key in the database before progressing on to any functionality.
For me it was a JS issue.
Take care of wrap function with jQuery that re-execute JS in wrapped content!
You might want to try and find out where it comes from using the debug_print_backtrace() function. (http://nl.php.net/manual/en/function.debug-print-backtrace.php
Had the same problem, with a certain action randomly running 2-3 times. I tracked down two causes:
Firefox add-on Yslow was set to load automatically from it's Preferences, causing pages to reload when using F5 (not when loading the page from the browser's address bar and pressing Enter).
I had a faulty css style declaration within the options of a $html->link(); in some cases it would end up as background-image: url('');, which caused a rerun also. Setting the style for the link to background-image: none; when no image was available fixed things for me.
Hope this helps. I know this is quite an old post, but as it comes up pretty high in Google when searching for this problem, I thought it might help others by still posting.
Good luck
Jeroen den Haan
I had a problem like this last week.
Two possible reasons
Faulty routes (DO check your routes configuration)
Faulty AppController. I add loads of stuff into AppController, especially to beforeFilter() and beforeRender() so you might want to check those out also.
One more thing, are where are you setting the Questioneer.id in your Session? Perhaps that's the problem?
Yes, it occurs when there is a broken link in the web page. Each browser deals with it variously (Firefox calls it 2x). I tested it, there is no difference in CakePHP v1.3 and v2.2.1. To find out who the culprit is, add this line to the code, and then open the second generated file in you www folder:
file_put_contents("log-" . date("Hms") . ".txt", $this->params['pass'] ); // CakePHP v1.3
file_put_contents("log-" . date("Hms") . ".txt", $this->request['pass'] ); //CakePHP v2.2.1
PS: First I blame jQuery for it. But in the end it was forgotten image for AJAX loading in 3rd part script.
I had the same problem in chrome, I disabled my 'HTML Validator' add on. Which was loading the page twice
I was having a similar issue, the problem seemed to be isolated to case-insensitivity on the endpoint.
ie:
http://server/Questionnaires/loadAvertisement -vs-
http://server/questionnaires/loadavertisement
When calling the proper-cased endpoint, the method ran once -whereas the lower-cased ran twice. The problem was occurring sporadically -happening on one controller, but not on another (essentially the same logic, no additional components etc.). I couldn't confirm, but believe the fault to be of the browser -not the CakePHP itself.
My workaround was assuring that every endpoint link was proper-cased. To go even further, I added common case-variants to the Route's configuration:
app/config/routes.php
<?php
// other routes..
$instructions = ['controller'=>'Questionnaires','action'=>'loadAvertisement'];
Router::connect('/questionnaires/loadavertisement', $instructions);
Router::connect('/QUESTIONNARIES/LOADADVERTISEMENT', $instructions);
// ..etc
If you miss <something>, for example a View, Cake will trigger a missing <something> error and it will try to render its Error View. Therefore, AppController will be called twice. If you resolve the missing issue, AppController is called once.

Categories