问题
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
回答1:
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');
}
回答2:
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.
回答3:
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");
来源:https://stackoverflow.com/questions/41423111/cant-use-session-at-codeigniter