can't use session at codeIgniter - php

I have a session in my form controller the session is create when the user save
the session affect the form page so my problem is :
if I loaded the page without clicking on save a undefined index[session index] error appears
so I created the session at the home page
but the problem is if I loaded the form page without visiting the home page at first the undefined index error appear
I tried to call the method session_start() but I got this error
A PHP Error was encountered
Severity: Notice Message: A session had already been started -
ignoring session_start() Filename: views/Form.php Line Number: 5

I strongly recommend using the default CI session library. You can autoload the session in autoload.php. Your session will start automatically, there is no need to call session_start().
Then replace $_SESSION['save']="true" with $this->session->set_userdata('save', 'true');.
I think you need to check if session['save'] is true or not, so beforehand you must declare by default that session['save'] is "false" in the default controller which is specified in the routes.php, and also make sure the session['save'] index is already defined in your form page controller, check like this:
if ($this->session->userdata('save')) {
// do something when exist
} else {
$this->session->set_userdata('save', 'false');
}

I am not sure why you are trying to implement your own session management within CI as one of the powerful tools CI offers is a flexible, simple yet powerful session management system.
Even so, surely a simple solution to your conundrum is to simply check if the session variable is set or not in your form, and if it is not set then set it to a value of 0. In your controller, you can deal with that, i.e. check if the value is 0, and if so, start a session and assign the session variable, or throw the user out, or do whatever you need you app to do when the session is not found, or is set to 0 indicating a session has not been activated.

Your session will start automatically, there is no need to call session_start() in every controller. codeigniter session library takes care of it.
First you have to load session library. application/config/autoload.php
$this->load->library("session");
if you have loaded already no need of loading again.
To set data in session
$this->session->set_userdata("KEY","VALUE");
To get data from session
$this->session->userdata("KEY");

Related

Issue with refreshing div with ajax [duplicate]

I have a one page website that uses AJAX to load new php files and update the display.
I start my php session on the main page but when I use ajax to update inner html I need those session variables for the new php file being loaded.
This post is similar to this one: PHP Session Variables Not Preserved . But I checked and my php.ini has session.use_cookies = 1
Main Page PHP:
<?php
session_start();
if(isset($_SESSION['views']))
{$_SESSION['views']=$_SESSION['views']+1;}
else
{$_SESSION['views']=1;}
?>
After User Input I use ajax to call a php file and load a subsection of the page:
<?php
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>
Can someone please tell me what important step I am missing? Thank you.
Update: After adding session_id() call to both the main and sub pages I see that both pages have the same Session_ID. However it still cannot pull the session variable and if i do assign it a value the two same name session variables stay independent of one another.
Answer to the question that this question created: I found that I had to set a static session_save path in my php.ini file. With most paid webhosting services they just have a default container for sessions but it is affected by load balancing. What a releif.
I think you're missing session_start() on the page that Ajax calls.
You need:
<?php
session_start();
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>
You need to start session session_start() in the other PHP file also, the one you are calling through AJAX.
I ran into what i thought was the same issue when running PHP 7 on IIS Server 2012 today.
I had added:
if(!isset($_SESSION))
{
session_start();
}
to the start of each AJAX file but kept recieving the following PHP Notice:
PHP Notice: A session had already been started - ignoring session_start()
A bit of searching lead me to this thread which pointed me in the right direction to resolving the issues I encountered. Hopefully the following information will assist others encountering the same issue.
After checking the session.save_path value was set, in my case C:\Windows\Temp, I thought it best to check the folder permissions match those of the user account I was running IIS under.
In my case it turned out that the directory I had nominated for session storage (in php.ini) did not have the same user (security permissions) assigned to it as the one which was running the IIS site.
Interestingly sessions worked fine when not using AJAX requests prior to me adding the new user permissions. However AJAX did not pick up the session until I had corrected the permissions issue. Adding the same user account that IIS is running under immediately resolved this issue.
In the case of using a paid web hosting service the default session save path is automatically set like this:
http://php.net/session.save-path
session.save_path = "/tmp/"
You need to place the static path to your root folder there.
You're trying to use existing session data from your application in an ajax call. To do that, change how you're calling session_start like so:
// With ajax calls
if (session_status()==1) {
session_start();
}
When making ajax calls to php scripts that need existing session data, use session_start after session_status.
http://php.net/session_status
Need to initialize the session before you trying to login through ajax call.
session_start();
Initialize on the top of the page from where you start the login ajax call.
So that the SESSIONID will be created and stored the browser cookie. And sent along with request header during the ajax call, if you do the ajax request to the same domain
For the successive ajax calls browser will use the SESSIONID that created and stored initially in browser cookie, unless we clear the browser cookie or do logout (or set another cookie)

codeigniter unsetting session works unexpectedly

I submit form to controller/complete action, set
$this->session->set_userdata('success', 3);
and then redirect to index action with redirect('controller', 'refresh');.
In my view I get
$success = $this->session->userdata('success');
do some work and then
$this->session->set_userdata('success', 0);
And it works fine, but when I reload page (it is an index action), I still get in $success 3, not 0. What am I missing?
I have seen many problems with codeigniter DB Session, and thus refuse to use it, to include the session not actually properly updating.
If you are interested I created a PHP Session based class that acts as a replacement, it benefits from backward compatability, but also a much easier way of using it.
Check out my Gist: https://gist.github.com/chazmead/1688becbcf11f897e962
To install you will need to replace the CI Session config in application/config/config.php to:
$config['session'] = (object)array(
'UID' => 'MY_SESSION_KEY',
'sess_expiration' => 7200,
'match_ip' => False,
'match_user_agent' => False
);
Then install the file to application/models/session.php
then instead of loading the CI session, just load this session model.
Using this is very easy, just assign variables to the session and it saves automatically, it also locks and unlocks the session so that async requests don't get locked up (which is a problem with PHP sessions)
For full backward compatability you may need to use $this->session = &$this->Session after loading the new model, otherwise you will have to make sure your calling session using Session (Uppercase S) as this is how CI models work. or install as a library instead..
The codeigniter by default managing session in COOKIE, more info
why the cookie value is not updated at once when i submit the form?
CI also provides setting to store session data in database table, if you store session in table this would work fine.
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html

PHP session variables not preserved with ajax

I have a one page website that uses AJAX to load new php files and update the display.
I start my php session on the main page but when I use ajax to update inner html I need those session variables for the new php file being loaded.
This post is similar to this one: PHP Session Variables Not Preserved . But I checked and my php.ini has session.use_cookies = 1
Main Page PHP:
<?php
session_start();
if(isset($_SESSION['views']))
{$_SESSION['views']=$_SESSION['views']+1;}
else
{$_SESSION['views']=1;}
?>
After User Input I use ajax to call a php file and load a subsection of the page:
<?php
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>
Can someone please tell me what important step I am missing? Thank you.
Update: After adding session_id() call to both the main and sub pages I see that both pages have the same Session_ID. However it still cannot pull the session variable and if i do assign it a value the two same name session variables stay independent of one another.
Answer to the question that this question created: I found that I had to set a static session_save path in my php.ini file. With most paid webhosting services they just have a default container for sessions but it is affected by load balancing. What a releif.
I think you're missing session_start() on the page that Ajax calls.
You need:
<?php
session_start();
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>
You need to start session session_start() in the other PHP file also, the one you are calling through AJAX.
I ran into what i thought was the same issue when running PHP 7 on IIS Server 2012 today.
I had added:
if(!isset($_SESSION))
{
session_start();
}
to the start of each AJAX file but kept recieving the following PHP Notice:
PHP Notice: A session had already been started - ignoring session_start()
A bit of searching lead me to this thread which pointed me in the right direction to resolving the issues I encountered. Hopefully the following information will assist others encountering the same issue.
After checking the session.save_path value was set, in my case C:\Windows\Temp, I thought it best to check the folder permissions match those of the user account I was running IIS under.
In my case it turned out that the directory I had nominated for session storage (in php.ini) did not have the same user (security permissions) assigned to it as the one which was running the IIS site.
Interestingly sessions worked fine when not using AJAX requests prior to me adding the new user permissions. However AJAX did not pick up the session until I had corrected the permissions issue. Adding the same user account that IIS is running under immediately resolved this issue.
In the case of using a paid web hosting service the default session save path is automatically set like this:
http://php.net/session.save-path
session.save_path = "/tmp/"
You need to place the static path to your root folder there.
You're trying to use existing session data from your application in an ajax call. To do that, change how you're calling session_start like so:
// With ajax calls
if (session_status()==1) {
session_start();
}
When making ajax calls to php scripts that need existing session data, use session_start after session_status.
http://php.net/session_status
Need to initialize the session before you trying to login through ajax call.
session_start();
Initialize on the top of the page from where you start the login ajax call.
So that the SESSIONID will be created and stored the browser cookie. And sent along with request header during the ajax call, if you do the ajax request to the same domain
For the successive ajax calls browser will use the SESSIONID that created and stored initially in browser cookie, unless we clear the browser cookie or do logout (or set another cookie)

Writing to a PHP Session Variable from Ajax

Ok, this is starting to annoy me, as it's quite simply and works elsewhere, but on this current task it doesn't, so here I go!
There is a main page which relies on either a session variable being set or not to display certain information.
Let's say this page is located here: http://dev.example.com/some_page.php
e.g.
if (isset($_SESSION["some_var"])) { /* it's set so do whatever */ }
else { /* not set so do whatever else.. */ }
There is an ajax page triggered by jQuery $.ajax() to call and set this session variable to null to change the action of the main page, let's say it's located here: http://dev.example.com/ajax/some_ajax_page.php
It's code looks like so:
<?php
if (!isset($_SESSION)) session_start();
$_SESSION["some_var"] = null;
When the main page is reloaded after the ajax is triggered, the session var "some_var" is still intact, but if it's echoed after the "null" in the ajax page then it is set to "null".
Basically it doesn't seem to write to the global session, only to the local path.
Does this make sense?
Any help please? Also if you want more clarification with anything let me know!
The session_start() function will handle the attempt to create and persist a session for you, as defined by PHP's configuration, or optionally at runtime if you set your own save handler. Make sure you read the documentation here:
http://us2.php.net/manual/en/function.session-start.php
For your code, you want to make sure to call session_start() at the beginning of any page in which you'd like to save or access session variables. So your page above may look like:
<?php
session_start();
$_SESSION['myvar'] = 'some value';
Then in a different page you can try to access that value:
<?php
session_start();
if ($_SESSION['myvar'] == 'some value') {
// do something
}
That should work fine.
Get rid of the check for session. If this is the only file your calling just do this:
<?php
session_start();
$_SESSION["some_var"] = null;
Also, are you using framework that auto-regenerates session ID on each request? If so, you'll might have problems.
If you have a dev machine to play with and permissions to do so, you can manually delete all sessions in the /var/lib/php/session/ directory. As you use your site, only one session file should be created. You can also inspect that file to see what is getting written and when.
Seems that you are using different sessions vars. One for the AJAX call and another for the normal pages calls. This may occur when you do not init both call in the same way (or using the same starting code that initializes the sessions)
Be sure to session_start() both calls using the same session_id.
// try in both calls
session_start();
echo session_id(); // must return the same id in both calls
Why don't you use unset? It is the proper way to do it.
Turns out the application I was working on had it's own session_handler and if it was not included before requesting the session data, it was always invalid, eventhough it was the same session_id.

Why can't I access session variables from my AJAX-called PHP script?

I have one PHP script with a session variable, set like so:
$_SESSION['VAR1'] = "test"
Now, I am using AJAX via a jQuery-initiated POST request, and so I have a script named ajax.php which has all the required functions.
And when I try access my session variable (echo $_SESSION['VAR1']) in ajax.php, it produces nothing.
Does session does not work from AJAX requests?
You need do this on every page that accesses the session before you access it:
session_start();
That means on both the page that sets the session variable and the AJAX page that tries to retrieve it. Both need to call session_start().
As long as the AJAX request calls a script in the same domain (and thus gets access to the session cookie) there is no reason why it couldn't get access to the session variables. An AJAX request after all is just another HTTP request.
Make sure that the domain names for both pages (i.e. the AJAX container and the AJAX script are same). Here is an example:
http://mydomain.com/login.php (set session variables here)
http://mydomain.com/ajax-container.php (session variables are visible here)
http://mydomain.com/ajax-script.php (session variables are visible here)
http://www.mydomain.com/ajax-script.php (session variables are NOT visible here)
Another one:
http://www.mydomain.com/login.php (set session variables here)
http://www.mydomain.com/ajax-container.php (session variables are visible here)
http://www.mydomain.com/ajax-script.php (session variables are visible here)
http://mydomain.com/ajax-script.php (session variables are NOT visible here)
I also caught myself on having one little, tiny, hard to see, space just before "< ? php " This ended up sending information back and disallowing the session to start because header information was already sent. May not be the case for anyone else, but it tripped me up and brought me to this page in search of an answer.
Make sure no content has been echoed (not even a whitespace) before calling session_start().
To be safe, put the code as the first code of whatever template you used for the page. The function will not work if content has been sent to the browser.
To test and see where the problem is, call the page as a stand-alone, instead of through AJAX and ensure that it works before AJAXing it.
An addendum to what Salman A wrote:
If you set a session variable in an https:// file and try to access it with a http:// file you will not be able to...
https://www.example.com/index.php - call session_start() and set session variable
http://ww.example.com/index_tmp.php - unable to access session variable
and vice versa...
http://www.example.com/index.php - call session_start() and set session variable
https://ww.example.com/index_tmp.php - unable to access session variable
Rather:
https://www.example.com/index.php - call session_start() and set session variable
https://ww.example.com/index_tmp.php - Able to access session variable
And:
http://www.example.com/index.php - call session_start() and set session variable
http://ww.example.com/index_tmp.php - Able to access session variable
My own error was BOM character in my ajax file.I was need to use session variable in a ajax called php file.I tried to start session by session_start() but "cannot modify header information" occurs.I removed BOM character and code works very well.
In jQuery or JavaScript, you can get the session value like this:
var StepIndexval = '<%= Session["StepIndex"].ToString() %>';
alert(StepIndexval);

Categories