I'm trying to get some values from my $_SESSION variable but it seems to be cleared everytime an AJAX request is initiated.
I have pasted the code below, any help much appreciated :
/*
* The input request from angularjs
*/
$data = file_get_contents("php://input");
$data = json_decode($data, true);
switch( strtolower($data['action']) ) {
case 'products': getAllProducts($data['fields']);
break;
default : echo json_encode(array('success' => false));
}
//fb is a firebug debug function, prints PHP vars to console.
fb($_SESSION['var'); //when loading the php file the first time $_SESSION is set
UPDATE
I'm using AngularJS for my AJAX calls, it works great but now I want to read data from my $_SESSION variable and all I get is an empty $_SESSION. Does this have anything to do with my file_get_contents("php://input");
SOLVED
I found the problem, the previous developer did not take into account that one might desire to include files from 2 levels deep :) As such, I scanned through the PHP error logs and saw that a previous script was not loading - this particular script was included with the session_start and $_SESSION variable values.
Checking the error logs will be my first priority from now on
I found the problem, the previous developer did not take into account that one might desire to include files from 2 levels deep :) As such, I scanned through the PHP error logs and saw that a previous script was not loading - this particular script was included with the session_start and $_SESSION variable values. Checking the error logs will be my first priority from now on
Related
I have a script in php that does some operations before insert the results into my table, but I'm trying to prevent the execution twice or more of the same script if i open it in more than one tab in my browser, I'm working to do a kind of trick to do this, for this I'm using sessions, I got a specific session variable that is updated when I run the script but my question is..
if I got something like this
session_start();
if (isset($_SESSION['lock'])) {
if ($_SESSION['lock'] === false) {
$_SESSION['lock'] = true;
}
}
that code is into a file that is executed with ajax request, once the variable has been updated with a new value it will be update globally?, I mean I have open two tabs with the same page (tab1 and tab2) after execute the script in tab1 when I do the same in tab2 the value $_SESSION['lock'] will be true or false?, I hope this explanation to be good, thanks.
NOTE: both tabs were opened at same time
Yes, changing $_SESSION is a global change for that particular user. But note that changes to $_SESSION are NOT pushed out to multiple windows "live". Only on subsequent hits in ANY window/tab will the new value have a chance to affect those tabs/windows.
Yes, sessions are bound to a unique User, so they are spreaded over tabs. Why don't you just test it though?
I am using AJAX to store the first 4 digits of a credit card in $_SESSION["first4"] number during the onBlur event. I have a sample which works flawlessly. Then I take that good code and stick it a shopping cart we purchased from Clearcart (we now own the code). The issue is that the $_SESSION variable is always empty in the AJAX php receiver program. Here is the entirety of the program:
$sessionName = "ClearCart20UserSession";
if (isset($_REQUEST[$sessionName])) session_id($_REQUEST[$sessionName]);
$started = session_start();
$_SESSION["first4"] = isset($_GET["first4"])?$_GET["first4"]:"";
After that fourth line of code the following variables are dumped: (i.e. these are output values not assignment statements)
$started = 1
session_id=4f920c1fe5e2078d95f7700ece674659
$_REQUEST=Array
(
[first4] => 5554
[PHPSESSID] => 4f920c1fe5e2078d95f7700ece674659
[ClearCart20UserSession] => 4f920c1fe5e2078d95f7700ece674659
)
$_SESSION=Array
(
[first4] => 5554
)
$_SESSION in the calling program literally contains thousand of variables. Yet, here in the receiver it is empty except for the variable I set.
Notes:
1) That is the same session_id/PHPSESSID as in the calling program - I have dumped it. (When I say calling program I mean the php program which generated the html form; obviously the actual 'calling' program is the javascript in the browser)
2) The http type and domain are identical (both are https:). I have put the receiver ajax program in the same directory as the caller just to eliminate any cross-domain issues.
3) The session save path is /tmp and when I look in that folder the sess_4f920c1fe5e2078d95f7700ece674659 file exists. (Although it seems smaller than I would expect with thousands of variables).
4) When I go back a page in my browser and then forward to re-show formerly saved session variables (i.e. things like form input values) they still exist so the AJAX recipient is not clearing $_SESSION as the empty array might imply.
5) The shopping cart uses cookies and the cookie values are correctly reflected in $_REQUEST as expected.
6) I added session_write_close() to the end of the main/caller program to ensure the session file is not open. Should not matter as the caller php terminates and nothing happens till the javascript event fires AJAX.
7) FWIW session.upload_progress.enabled is on.
8) Curiously the shopping cart uses AJAX for its own purposes which I believe is working fine. Regardless, I don't see how that could impact me - its completely different AJAX called and received by different javascript and php respectively.
9) As mentioned above, this virtually identical code works in a test sample I developed where I even mimic using cookies.
10) I have read several dozen postings on this issue but none have fixed my problem. Most seem to be related to not using session_start or having the right session_id.
What else can I try?
Found the problem: the shopping cart software changed the session folder with this line of code:
session_save_path("tmpsession");
Hence, even though the session_id's were identical the session files were stored in two different folder locations (the AJAX file was in /tmp and the main calling program was using www/tmpsession).
I'm facing the weirdest issue I've ever seen with PHP. I will try to be really exhaustive because each detail can count.
I have 3 PHP pages, and their HTML is generated using Smarty. They all call session_start() at their top.
the first page can be heavy to load, it displays a big amount of clickable pictures that are previews of PHP complex objects
if a picture is chosen it leads to the second page with a specific URL.This page will generate a PHP object related to the URL info (so this page does not need info from previous page to work. If you copy-paste this URL at anytime it will work). This object will be stored into $_SESSION with a unique id.
the third page is included as an img src in the second page's HTML code (generated with Smarty). This is a PHP page having the object's session id in URL parameter and reading the object's info in $_SESSION, creating it's image preview and turns into an image with header('Content-type: image/jpeg').
To sum up :
heavy first page => second page creating and storing a PHP object into $_SESSION => third page, included in second page's HTML code, searching for this object and creating a preview.
The problem is, sometimes, this third page is trying to load the object in $_SESSION and it's just not there !
Some facts :
the problem never occurs when the second page is loaded as a stand-alone with its own URL
the problem only occurs randomly when the heavy first page starts loading images and we furiously click on one of the first ones to appear
whatever the situation is, if I dump my $_SESSION variables at the very end of the second page I can ALWAYS see the generated object in my session
So it seems that the issue is located between the very end of the second page and the beginning of the third, but all of this related to the activity of the first one !
All I know is that it is linked to a fast navigation between pages.
I've tried almost everything :
session_write_close() everywhere it's possible (at the end of my pages before/after smarty display, then at the beginning before session_start())
add exit() at the end of my scripts
even sleep(1) at the beginning of the third in case session close operation needs more time
Nothing works. I have no more clues ... Maybe Smarty ? Maybe some odd PHP session behaviour named bug #4454 somewhere ?
Thanks a lot in advance for helping me with this.
Edit : piece of code after serialize() chat
/* ===== Page2.php ===== */
/*creating object $card and setting some values ...*/
/*calling the function that gives the card preview*/
$assigns['front'] = $card->getPreviewURL();
/*other stuff ... assign $assigns to smarty ... etc*/
/* ===== Card object class ===== */
function getPreviewURL()
{
$_SESSION['products'][$this->getObjectId()] = serialize($this);
$url = '/page3.php?s='.$this->getObjectId();
return $url;
}
/* ===== Page2.html ===== */
img src="{$front}" alt="toto"
/* ===== Page3.php ===== */
/*getting id value and reading session*/
if(!empty($_GET['s'])) {
session_write_close();
$session = new Session;
if(!empty($_SESSION['products'][$_GET['s']])) {
$product = unserialize($_SESSION['products'][$_GET['s']]);
}
else {
log('$_SESSION[products]['.$_GET['s'].'] does NOT exist');
header("Status: 404 Not Found");
exit;
}
}
and when bug occurs, I get :
page2.php debug log :
Session value : [o20aee110e0853e74da4d17c9b7ab3075]=>O:8:"Postcard":19:{s:4:"tmpl";O:16:"PostcardTemplate":20:{s:2:"id";s:3:"152";s:2:"or";i:0;s:3:"ord";s:2:"14";s:11:"description";s:0:"" ... etc
page3.php debug log :
$_SESSION[products][o20aee110e0853e74da4d17c9b7ab3075] does NOT exist
Probably, the problem is, that PHP tries to unserialize your object but cannot find the class definition.
You can do one of the following two things:
serialize() the object manually before you put it into the session and unserialize() it after you loaded the class definition.
Or: Use autoloading.
This may be a n00b topic but, anyways, I have been having a rather difficult and strange time with this bug. Basically I was working on a controller method for a page that displays a form. Basically, I was debugging the form's submitted data by var dumping the form input using codeigniter's $this->input->post function like so:
var_dump($this->input->post('first_name'));
Every other day this has worked, but today I was finding that when I dumped post variables to the browser it would return false as if they had no values even though they did have values when I submitted the form. Then I tried accessing the variables through PHP's POST superglobal array directly like so:
var_dump($_POST['first_name']);
and that returned empty as well so then I tried dumping the entire post array like so:
var_dump($_POST);
and it was empty as well despite the fact that I filled out the entire form. Nevertheless, the records in my MySQL database were being updated (which means that the form was submitting even though my $_POST variables appeared empty).
Also, I reasoned that normally, if I var dumped variables in the controller function before a redirect function call that it should give me a 'Headers already sent' error but it never did. It just redirected me to the supposed success page instead of dumping my variables.
So for the about 2 hours I thought that my POST data wasn't being sent and re-checked the code for errors and began commenting out statements one by one until I could find the culprit statement in my script.
Finally, I commented out a chunk of code that sets a success message an redirects, like so:
/*
if($record_updated_successfully)
{
$this->session->set_flashdata('success', $this->lang->line('record-updated-successfully'));
}
redirect('admin/success_page');
*/
and only then did the script start dumping out all my previous variable dumps using codeigniter's $this->input->post function as well as the $_POST superglobal array.
So ok, if the script does indeed redirect me despite the variable dumps sending output before headers are sent then I can see why the $_POST variables would appear empty.
So then the real question is why the script would still redirect despite my sending of output before headers are sent? Has anyone ever experienced this?
Any help with this would be appreciated.
EDIT: with respect to loading the view here's a simplified version of my script looks like
with the debugging var dump statements:
function some_controller_method() {
var_dump($this->input->post());
var_dump($_POST);
// some code
if($this->input->post('form_action') == 'update record') {
// code that runs when the form is submitted
/*
* ...
*/
if($record_updated_successfully)
{
$this->session->set_flashdata('success', $this->lang->line('record-updated-successfully'));
}
redirect('admin/success_page');
}
$this->load->view('my-view-file.php');
}
While I can't be sure, I'm going to assume you were outputting things like the var_dump() in your view file. A view is not executed at the time you call it, for example:
$this->load->view('some_view');
echo "hi!";
In a controller will not result in the contents of some view followed by "hi". It will results in "hi" followed by the contents of some view. The view is actually output after everything else in the controller has run.
This is the only thing that comes to mind with the information you've presented. I'd have to see more code to offer a different diagnosis.
I had "the same" problem and I found an unset() function in a loop in my code. Perhaps this will help.
I am working on my personal site, where I want to store my customers recent search result limited to that particular session.
I am using PHP platform and Javascripts.
Here is an example of what I am exactly looking at :
It stores your previously searched domain name for that particular session so that user can make decision by comparing those results.
Thanks.
EDIT- Well Thanks for all of your answers and suggestions.
But If you have noticed
above example
It looks like some kind of script loading a new content on the same page without refreshing it and keeping previous search content <div> as it is.
How to achieve this using javascripts or some sort of div layer ????
UPDATE START
This example uses page reload. If you want to do it without page reload, you can but you'll have to use AJAX to load new search results. But then, it's not a PHP question. I suggest looking at jquery library, as it makes it easy. Tutorials: http://docs.jquery.com/Tutorials and e.g. this one ( http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax ).
When loading data via AJAX, the page rendering result (in my example search.php) should return only HTML for results part, not whole HTML page. This is generally a first part of my tutorial (without session).
But I really think that AJAX in here is not really needed. Session is more reliable and allows access to your page from older / mobile browsers where not always JS works correctly.
UPDATE END
Ok then. Let's try the simple tutorial then. Sorry if too simple, but I don't know your exact level.
PHP has mechanism called sessions. In reality they are just bytes stored on server. Server knows which session is for each client by reading session cookie from client browser.
Not every page uses sessions (not every page needs it, and session uses server space, even if only temporarily), session is not enabled by default. To turn on session you use command
<?php session_start(); ?>
In most cases this is either run by PHP framework you use, or put near the top of your site. Session is definitely needed if you want to authenticate user somehow. Or in your case :)
To access session you can use superglobal $_SESSION variable (superglobal means that you can access it anywhere). It's an array, so session element will be e.g. $_SESSION['search'] etc.
As example, let's assume that your page looks like that
<html>
...
<form action="search.php" method="post">
Search: <input type="text" name="searchQuery" />
<input type="submit" value="Search" />
</form>
...
</html>
this very form will send user search to file named search.php. It can be the same file where the form resides - in simplest case when you put both your code and HTML in one file. Beginners often use this schema, although it's not advisable as result is a mess and hard to further change.
In search.php then, you'll use similar code:
<?php
if (!empty($_POST['searchQuery'])) //we have a new search
{
$result = do_search($_POST['searchQuery']);
}
?>
Then, somewhere below you'll display your search result ($result variable). do_search() function is your search mechanism, I guess you have it somewhere. You may have it not 'wrapped' in a function, then I advise to create it like that, it's much more useful.
function do_search($searchQuery)
{
...
return $result;
}
mind it, the above code doesn't use sessions yet. Let's add saving previous search results in session. The code may then look like that:
<?php
session_start(); //Starting session
//let's create session variable used to store results
if (!isset($_SESSION['searches']))
$_SESSION['searches'] = array();
if (!empty($_POST['searchQuery'])) //we have a new search
{
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value, delete previous result from sesion
{
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
$result = do_search($_POST['searchQuery']);
//Let's add new search on the begining of session array to make iterations easier.
$result = array($_POST['searchQuery'] => $result); //convert result to same format as session table
$_SESSION['searches'] = array_merge($result, $_SESSION['searches']);
}
?>
In display you'll now not iterate on $result variable as before, but instead you will do something like
foreach ($_SESSION['searches'] as $query => $result)
{
...//display of single result
}
I haven't tested following code and it's not a full program. Parts to display result and to do actual search are not described but I guess you have them already prepared. Also, this is only one possible approach of countless possibilities. But I hope this helps :)
Possible modification - now I always perform search, even if user already searched on this term. You may want to receive the result from cache without second search. Then the code will look like
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value
{
$result = $_SESSION['searches'][$_POST['searchQuery']];
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
else
{
$result = do_search($_POST['searchQuery']);
}
For more in-depth information about sessions and some other constructs used in my example I suggest PHP manual
http://pl.php.net/manual/en/book.session.php
and various tutorials over the network. Or you can add a comment here :)
Put this code near the beginning of your script(s):
if (!isset($_SESSION['previous_searches']) || !is_array($_SESSION['previous_searches'])) {
$_SESSION['previous_searches'] = array();
}
[edit]
This code snippet checks if if there is already an array with prevous searches and if not it will be created.
[/edit]
Then when the user hits the search page put this code in the receiving script of the search:
$_SESSION['previous_searches'][] = $_GET['what_ever_your_search_value_might_be'];
[edit]
This code snippet adds the current search value to the and of the array with previous search values
[/edit]
Now you have all previous search values in $_SESSION['previous_searches']
If your website is a web application where you never reload the page nor change the page, you can keep it JavaScript in a global store (declare at top level something like var StoredSearch = []; and use it). If not, then use $_SESSION to store this and AJAX to save/load searches from JavaScript to PHP.