accessibilty issue with codeigniter session library - php
I'm working on user login system in codeigniter. When user clicks on login button the username and password are verified and the data is store in $this->session->set_userdata($arr); session library and the page redirects to home.php. Till here works fine but when is try to access the session in home.php as print_r($this->session->userdata);. it give me this errors
Here is the Controller code : Login.php
function login_user(){
$login_btn = $this->input->post('login_btn');
if($login_btn == TRUE){
$arr['login'] = array(
'username'=>$this->input->post('username'),
'password'=>$this->input->post('password')
);
$query = $this->Login_model->users_login($arr);
if($query->num_rows() > 0 && $query->num_rows() == 1){
$this->load->library('session');
$this->session->set_userdata($arr);
redirect('Login/redirec_To_home','refresh');
}
else
{
$this->index();
}
}
else
{
$this->index();
}
}
function redirec_To_home(){
$this->load->view('login/home');
}
Here is the view html file name : path views/login/home.php
<?php
print_r($this->session->userdata); //ERRORS SHOWN IN THIS LINE NUMBER : 13
?>
THANKS IN ADVANCE
Please go to application/config/autoload.php in your project directory and search libraries, after that add session to this line which will look like this.
$autoload['libraries'] = array('session');
In the __construct area you need to reload the session library using get instance in libraries
https://www.codeigniter.com/user_guide/general/ancillary_classes.html
https://www.codeigniter.com/user_guide/general/creating_libraries.html#utilizing-codeigniter-resources-within-your-library
class Example {
protected $CI;
// We'll use a constructor, as you can't directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
$this->CI->load->library('session');
$this->CI->load->model('login_model');
}
public function somefunction()
{
$this->CI->input->post('username');
$this->CI->input->post('password');
$user_model = $this->CI->login_model->user_login();
$sesstion_data = array('user_id' => '1');
$this->CI->session->set_userdata($sesstion_data);
}
}
Related
CodeIgniter session Data showing null during authentication
I'm trying to send the session variable to another controller but when i use r_print() it shows nothing and there is condition applied which returns null. <?php // library/login_lib.php class Login_lib { public function logged_in() { $CI = & get_instance(); return ($CI->session->userdata('userdata')['is_logged_in']) ? $CI->session->userdata('userdata')['is_logged_in'] : Null; } } ?> <?php // another file common_helper.php if( !function_exists('authentication_user') ) { function authentication_user() { $CI = & get_instance(); if( !$CI->login_lib->logged_in() ) { $CI->session->set_flashdata('error', 'Please login with username and password'); if( $CI->input->is_ajax_request() ) { echo 'session_expire'; die(); } else { redirect(); } } } } There is another controller called Dashboard where i calling the above function authentication_user(). What i want now i want to call true from the login_lib which i am not actually. I don't know why its blocking to view the Login session. Thanks in advance
return $CI->session->userdata('is_logged_in') ? $CI->session->userdata('is_logged_in') : Null; syntax for getting session data in codeigniter is $this->session->userdata('session_key');
Added new method to the controller doesn't work in codeigniter
I am working on an existing project developed by codeigniter 2.1.4. When I add a new method to a controller and run it to the browser, it shows nothing. Even other methods under that controller also don't run if new method added to that controller. These controllers extends the following controller: <?php class MY_Controller extends CI_Controller { public $data = array(); public $allowedUrl = array( "super admin" => array("case_controllerler/deleteSingleCase","case_controller/quickPendingCaseSearch","case_controller/checkUniqueCaseNumber","case_controller/kharijCase","admin/index","case_controller/viewSatalementKhatianCopyApplication", "admin/saveAdmin","admin/addUser", "admin/allAdmin", "admin/suspendUser", "admin/activeUser", "admin/CustomSearchGL","admin/showMethod","admin/CustomSearchAction","admin/deleteUser","admin/showAllComplain","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated","case_controller/downloadPendingCase", "case_controller/addCase", "case_controller/store_data", "case_controller/caseSuccessfullyAdded", "case_controller/createCalender", "case_controller/workingDaysCalender", "case_controller/editPendingCase","case_controller/saveEditedPendingCase","case_controller/EditmissCase","case_controller/UpdateMisccase", "case_controller/pending", "case_controller/allCase", "case_controller/searchCase", "case_controller/singleCase","case_controller/testAjax","case_controller/DeleteLandData","case_controller/SaveNEwLandInfo","case_controller/DeleteApplicantinfo", "case_controller/nextDateFromGivenDate","case_controller/downloadArchiveCase","case_controller/sendSms","case_controller/secondSms","case_controller/thirdSms","case_controller/fourthSms","case_controller/fiveSms","case_controller/CustomSms","case_controller/monthAllreadyExit", "register_control/AddTohsil","register_control/TohsilEntry","register_control/EditTohsil","register_control/updatetohsil", "register_control/AddMouja","register_control/MoujaEntry","register_control/EditMouja","register_control/updateMouja", "register_control/AddMutationAsistant","register_control/MutationAsistantEntry","register_control/EditMutationAsistant","register_control/updateMutationAsistant", "register_control/AddKhotiyan","register_control/moujaquery","register_control/saveKhotiyan","register_control/saveKhotiyanFile", "register_control/FindKhotiyan","register_control/SearchKhotiyan","register_control/DeleteKhotiyan","register_control/Editkhotiyan", "register_control/AddNewKhotiyanUnderKhotiyanId","register_control/saveNewKhotiyan","register_control/UpdateKhotiyan","register_control/Getjolmohol", "register_control/Tamil","register_control/EntryTamilFormat","register_control/createcellfortamil","register_control/editTamil","register_control/UpdateTamil","register_control/DeleteTamil","register_control/Imgdownload", "dashboard/DashboardHome","dashboard/viewFullreport","dashboard/tohsilviewlist","dashboard/tohsilviewlistoverdate","dashboard/namjariviewlist","dashboard/namjariviewlistoverdate","dashboard/kanongopendingviewlist","dashboard/kanongooverdateviewlist","dashboard/aclandPendingeviewlist","dashboard/aclandoverdateviewlist","dashboard/waitingpendingviewlist","dashboard/waitingooverdateviewlist", "admin/DeleteComplains","admin/fullviewcomplains", "register_nine/Newentry","register_nine/SaveData","register_nine/Search","register_nine/viewapplication", "register_nine/editapplication","register_nine/Deleteapplication","register_nine/Preview","register_nine/UpdateApplication", "register_nine/SearchForPreview","register_nine/paginationData","admin/GovLandEntry","admin/savegovtLandInfo","admin/GovLandQuery","admin/govtLandInfoQuery","admin/EditGovtLand", "admin/UpdategovtLandInfo","admin/DeleteGovtLandInfo","admin/govtLandInfoQueryByType", "case_controller/AddmissCase","case_controller/SaveMissCase","case_controller/MIssCassUpdate","case_controller/UpdateInfoMissCase","case_controller/MiscSmsToplaintiff", "case_controller/EditMIssCaseUpdate","case_controller/UpdateStatus","case_controller/DeletemissCasestatus","case_controller/CheckGovtLand", "case_controller/FinishMisscase","case_controller/DeletemissCase","case_controller/ArchivemissCase","case_controller/ViewMIssCassUpdate","case_controller/SearchActionByNameOrNId","case_controller/SearchActionBydag", "case_controller/SearchmissCase","case_controller/SearchMisscaseAction","case_controller/viewPorcaApplication","case_controller/DeletePorcaapplication","case_controller/ArchivePorcaApplication","case_controller/approvalsms", "case_controller/ApprovePoRcaApliCation","case_controller/fullviewPrcaApplication","register_control/RemoveKhotiyanFile","case_controller/SaveMissCaseAttchment", "register_control/DeleteKHotiyanFile","register_control/ViewTamil","register_control/NewAddKhotiyanFile","register_control/TamilDownload","register_control/RegisterONe","register_control/FileInventory" ,"other_registers/EntryDailyIncome","other_registers/SaveDailyINcome","other_registers/inqueryAndSubmit","other_registers/SearchActionOfInquery","other_registers/DeliveryToBank","other_registers/deliverySuccess", "other_registers/searchCashRegister","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthreebyStauts","other_registers/registerseventeenOfTohsil","other_registers/DemandRegister","other_registers/miscellenousPaymentRegister", "other_registers/registerseventeenOfAcland","admin/showAllOpinion","admin/Deleteopinion","admin/fullviewopinion","mutation_controller/DownloadMutationApplication","mutation_controller/AllMutationApplications","mutation_controller/DetailsMutationAppliCation", "mutation_controller/accecptApplicationSms","mutation_controller/DeleteMutationApplication","dashboard/TohsilPieChart","other_registers/SavedemandRegisterSix","other_registers/SearchAndDelivaryRegisterSix" ,"other_registers/SearchActionOfInqueryRegisterSix","other_registers/RegisterSixDelivery","other_registers/registerSixdeliverySuccess","other_registers/SavePaymentRegisterSeven", "other_registers/SearchAndDelivaryRegisterSeven","other_registers/SearchActionOfInqueryRegisterSeven","other_registers/RegisterSevenDelivery","other_registers/registerSevendeliverySuccess","case_controller/ChangeMutationAsistant", "case_controller/ActionChangeMutationAsistant","case_controller/FeedbackMiscCaseUpdate","case_controller/FeedbackUpdateInfoMissCase","admin/EditUser","admin/updateAdminInfobySuperAdmin", "case_controller/EditMIssCaseUpdateFeedback", "case_controller/UpdateStatusFeedback","case_controller/PrintMIsscassInformation","case_controller/viewArchiveCase","case_controller/deleteArchiveSingleCase","case_controller/RuningMiscCase","dashboard/CaseCounter", "other_registers/deleteDailyEntryRegisterThree","other_registers/deleteDailyEntryRegistersix","other_registers/deleteDailyEntryRegisterseven","case_controller/fullviewArchivePrcaApplication","case_controller/OrderSheet","case_controller/SaveOrderInfo","case_controller/PrintOrderSheet", "case_controller/ViewLedger","case_controller/ProposalView","case_controller/SaveProposalInfo","case_controller/PrintProposalView","case_controller/CaseNotice","case_controller/PrintNoticeView","case_controller/SecondPagePrintProposalView", "case_controller/UpdateCaseLandInfo","case_controller/SaveScratchMap","case_controller/UpdateCaseApplicantInfo","case_controller/TohsilWisePendingCaselist"), "admin" => array("case_controller/addCase","case_controller/organizeDateFormat","case_controller/createCalender","case_controller/EditmissCase","case_controller/UpdateMisccase","case_controller/DeleteLandData","case_controller/SaveNEwLandInfo","case_controller/DeleteApplicantinfo", "case_controller/assendingCalender","case_controller/monthAllreadyExit","case_controller/changeDateFromat","case_controller/testAjax","case_controller/nextDateFromGivenDate", "case_controller/store_data","case_controller/caseSuccessfullyAdded","case_controller/allCase","case_controller/searchCase","case_controller/singleCase", "case_controller/pending","case_controller/quickPendingCaseSearch","case_controller/kharijCase","case_controller/editPendingCase","case_controller/saveEditedPendingCase", "case_controller/downloadArchiveCase","case_controller/downloadPendingCase","case_controller/sendSms","case_controller/secondSms","case_controller/thirdSms", "case_controller/fourthSms","case_controller/fiveSms","case_controller/CustomSms","case_controller/checkUniqueCaseNumber","case_controller/AddmissCase","case_controller/MiscSmsToplaintiff","case_controller/ViewLedger","case_controller/CaseNotice", "case_controller/SaveMissCase","case_controller/MIssCassUpdate","case_controller/UpdateInfoMissCase","case_controller/EditMIssCaseUpdate","case_controller/UpdateStatus", "case_controller/FinishMisscase","case_controller/ArchivemissCase","case_controller/ViewMIssCassUpdate","case_controller/RuningMiscCase","case_controller/SaveMissCaseAttchment", "case_controller/SearchmissCase","case_controller/SearchMisscaseAction","case_controller/viewPorcaApplication","case_controller/ArchivePorcaApplication", "case_controller/ApprovePoRcaApliCation","case_controller/fullviewPrcaApplication","case_controller/SearchActionByNameOrNId","case_controller/SearchActionBydag", "case_controller/approvalsms","case_controller/ChangeMutationAsistant","case_controller/ActionChangeMutationAsistant","case_controller/FeedbackMiscCaseUpdate", "case_controller/FeedbackUpdateInfoMissCase","case_controller/EditMIssCaseUpdateFeedback","case_controller/UpdateStatusFeedback","case_controller/PrintMIsscassInformation", "case_controller/viewArchiveCase","case_controller/RuningMiscCase","case_controller/viewSatalementKhatianCopyApplication","case_controller/fullviewArchivePrcaApplication", "dashboard/DashboardHome","dashboard/viewFullreport","dashboard/tohsilviewlist","dashboard/tohsilviewlistoverdate","dashboard/namjariviewlist", "dashboard/namjariviewlistoverdate","dashboard/kanongopendingviewlist","dashboard/kanongooverdateviewlist","dashboard/aclandPendingeviewlist", "dashboard/aclandoverdateviewlist","dashboard/waitingpendingviewlist","dashboard/waitingooverdateviewlist","dashboard/TohsilPieChart","dashboard/CaseCounter", "mutation_controller/AllMutationApplications","mutation_controller/DetailsMutationAppliCation","mutation_controller/DownloadMutationApplication", "mutation_controller/accecptApplicationSms","mutation_controller/DeleteMutationApplication","mutation_controller/MutationForm", "other_registers/EntryDailyIncome","other_registers/SaveDailyINcome","other_registers/inqueryAndSubmit","other_registers/SearchActionOfInquery", "other_registers/searchCashRegister","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthreebyStauts", "other_registers/registerseventeenOfTohsil","other_registers/DemandRegister","other_registers/miscellenousPaymentRegister","other_registers/registerseventeenOfAcland", "other_registers/SavedemandRegisterSix","other_registers/SearchAndDelivaryRegisterSix","other_registers/SearchActionOfInqueryRegisterSix","other_registers/RegisterSixDelivery", "other_registers/registerSixdeliverySuccess","other_registers/SavePaymentRegisterSeven","other_registers/SearchAndDelivaryRegisterSeven", "other_registers/SearchActionOfInqueryRegisterSeven","other_registers/RegisterSevenDelivery","other_registers/registerSevendeliverySuccess", "register_control/moujaquery","register_control/getmoujaAndMObile","register_control/AddKhotiyan","register_control/saveKhotiyan","register_control/saveKhotiyanFile", "register_control/NewAddKhotiyanFile","register_control/FindKhotiyan","register_control/SearchKhotiyan","register_control/Editkhotiyan","register_control/UpdateKhotiyan", "register_control/Tamil","register_control/createcellfortamil","register_control/EntryTamilFormat","register_control/editTamil","register_control/UpdateTamil", "register_control/ViewTamil","register_control/Imgdownload","register_control/TamilDownload","register_control/RegisterONe","register_control/Getjolmohol", "admin/index","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated","admin/GovLandEntry","admin/savegovtLandInfo","admin/GovLandQuery","admin/govtLandInfoQuery", "admin/EditGovtLand","admin/UpdategovtLandInfo","admin/govtLandInfoQueryByType","admin/allAdmin","admin/CustomSearchGL","admin/showMethod","admin/CustomSearchAction", "register_nine/Newentry","register_nine/Search","register_nine/viewapplication","register_nine/editapplication","register_nine/UpdateApplication", "register_nine/Preview","register_nine/SearchForPreview","register_nine/paginationData","case_controller/UpdateCaseLandInfo","case_controller/SaveScratchMap","case_controller/UpdateCaseApplicantInfo"), "general user" => array("case_controller/quickPendingCaseSearch","case_controller/kharijCase","case_controller/pending", "case_controller/allCase", "case_controller/searchCase", "case_controller/singleCase", "admin/index","case_controller/downloadPendingCase","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated",) ); public function __construct() { parent::__construct(); $this->isLoggedIn(); $this->isPermitedToAccess(); } public function isLoggedIn() { if ($this->session->userdata('logged_in') === FALSE) { redirect('login/index'); } } //end of the is logged in public function isPermitedToAccess() { $userType = $this->session->userdata("type"); $currentUrl = $this->uri->segment(1) . "/" . $this->uri->segment(2); if (array_search($currentUrl, $this->allowedUrl[$userType]) === FALSE) { redirect("admin/index"); } } } I tried to add my new method to $allowedUrl variable. But it didn't work. Can any one please give me any idea to solve this problem. I am stuck on it.
Did you try to assign the value for $allowedUrl inside __construct function, I think it will work!
Call to a member function insert() on null. Codeigniter
Hi everyone I am getting the following error when I submit my form for my CI 3 website: Fatal error: Call to a member function insert() on null This error is occurring on line 20 which is: $query = $this->db->insert('temp_subscribed_users', $data); Here is the full function: public function add_temp_user($key) { echo "hello"; $data = array( 'TEMP_EMAIL' => $this->input->post('email'), 'TEMP_KEY' => $key ); echo var_dump($data); $query = $this->db->insert('temp_subscribed_users', $data); if($query) { return true; }else{ return false; } } I am not sure what it means by null. The table name is correct and I did a var_dump to confirm that the array is being populated. I also made sure that I am getting into the function by echoing "hello" and it is outputting onto the page. Any help is appreciated thank you! Additional info: Running using XAMPP localhost.
load database and then call insert function. Codeigniter does not load database automatically for the performance issue. $this->load->database(); $query = $this->db->insert('temp_subscribed_users', $data);
Well first of all you're not utilizing the MVC model of codeigniter. Controller is for functions, Model is for the database connections. First autoload your database, If not just put it in the code. But here is how it should look like. CONTROLLER FUNCTION public function add_temp_user($key) { echo "hello"; $this->load->model('MY_MODEL'); //If you're not autoloading db include the next line //$this->load->library('database'); $data = array( 'TEMP_EMAIL' => $this->input->post('email'), 'TEMP_KEY' => $key ); echo var_dump($data); //If you confirmed the data var dumped $success = $this->MY_MODEL->insert_to_db($data); if($success == true) { //Do something } else { //Do something } } MODEL public function insert_to_db($data) { $query = $this->db->insert('temp_subscribed_users', $data); // if($query) { return true; } else { return false; } } Make sure the TEMP_EMAIL and TEMP_KEY are the columns in your database and temp_subscribed_users is your table name
Try to solve your problem by getting into the autoload.php in the config folder and add database on the array for libraries, like this: $autoload['libraries'] = array('database');
Please check whether object is created or not. Check that object is available in that class
Fatal error: Call to a member function login() on a non-object in
Got an issue with a web app that I've inherited as a project and unfortunately I can't trace the error. It seems that the model isn't being loaded but I could be wrong. Any help would be great. code is: public function login() { //If request is post then user is trying to login, so process the login info if ($_SERVER['REQUEST_METHOD'] === 'POST') { //Run the model method ::login $login_successful = $this->User->login(); // check login status if($login_successful) { // if YES, then move user to dashboard/index (btw this is a browser-redirection, not a rendered view!) header('location: ' . URL . 'passwords/index'); } else { echo "Incorrect user / pass combination entered. Please try again."; } } } and the model function is: public function login() { $username = $_POST['data']['User']['username']; $password = $_POST['data']['User']['password']; $bind = array( ":username" => "$username", ); $result = $this->select("users", "username = :username", $bind); //Check the password returned from the db against the password entered if (Bcrypt::checkPassword($password, $result[0]['password']) == true) { Session::init(); Session::set('user_logged_in', true); Session::set('user_id', $result[0]['id']); Session::set('user_name', $result[0]['username']); Session::set('user_permission', $result[0]['permission']); Session::set('user_role', $result[0]['role']); return true; } else { return false; } } also I've noticed that the controller and model both have a function called login.] Thanks
The reason is $this->User is not a valid class instance. Make sure that it is an object. Try var_dump($this->User); die(); //Run the model method ::login $login_successful = $this->User->login(); And you will see that there is no instance there. What to do? Find the place where you expect your model being initialized. Check, why it is not.
Dynamic global array in codeigniter
I want a global array that I can access through controller functions, they can either add or delete any item with particular key. How do I do this? I have made my custom controller 'globals.php' and added it on autoload library. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); $notification_array = array(); $config['notification'] = $notification_array; ?> following function on controller should add new item to my array function add_data(){ array_unshift($this->config->item('notification'), "sample-data"); } after add_data adds to the global array, whenever following function is called from client, it should give the updated array to the client. function send_json() { header('content-type: application/json'); $target = $this->config->item('notification'); echo json_encode($target); } But my client always gets empty array. How can I make this happen? Please help.
Hi take advantage of OOP, like this // put MY_Controller.php under core directory class MY_Controller extends CI_Controller{ public $global_array = array('key1'=>'Value one','key2'=>'Value2'): public function __construct() { parent::__construct(); } } //page controller class Page extends MY_Controller{ public function __construct() { parent::__construct(); } function send_json() { header('content-type: application/json'); $target = $this->global_array['key1']; echo json_encode($target); } }
One solution I came up is to use session, its easy to use and its "fast" you need to do some benchmarking. As I commented on both answers above/below there is no way you get same data in different controllers just because with each request everything is "reset", and to get to different controller you need to at least reload tha page. (note, even AJAX call makes new request) Note that sessions are limited by size, you have a limit of 4kb (CodeIgniter stores session as Cookie) but wait, there is way around, store them in DB (to allow this go to config file and turn it on $config['sess_use_database'] = TRUE; + create table you will find more here) Well lets get to the answer itself, as I understand you tried extending all your controllers if no do it and place some code in that core/MY_Controller.php file as follows: private function _initJSONSession() { //this function should be run in MY_Controller construct() after succesful login, $this->_initJSONSession(); //ignore return values $json_session_data = $this->session->userdata('json'); if (empty($json_session_data )) { $json_session_data['json'] = array(); //your default array if no session json exists, //you can also have an array inside if you like $this->session->set_userdata($ses_data); return TRUE; //returns TRUE so you know session is created } return FALSE; //returns FALSE so you know session is already created } you also need these few functions they are self explainatory, all of them are public so you are free to use them in any controller that is extended by MY_Controller.php, like this $this->_existsSession('json'); public function _existsSession( $session_name ) { $ses_data = $this->session->userdata( $session_name ); if (empty( $ses_data )) return FALSE; return TRUE; } public function _clearSession($session_name) { $this->session->unset_userdata($session_name); } public function _loadSession($session_name) { return (($this->_existsSession( $session_name )) ? $this->session->userdata($session_name) : FALSE ); } the most interesting function is _loadSession(), its kind of self explainatory it took me a while to fully understand session itself, well in a few words you need to get (load) data that are in session already, do something with it ([CRUD] like add new data, or delete some) and than put back (REWRITE) all data in the same session. Lets go to the example: keep in mind that session is like 2d array (I work with 4+5d arrays myself) $session['session_name'] = 'value'; $session['json'] = array('id' => '1', 'name' => 'asok', 'some_array' => array('array_in_array' => array()), 'etcetera' => '...'); so to write new (rewrite) thing in session you use { $session_name = 'json'; $session_data[$session_name] = $this->_loadSession($session_name); //manipulate with array as you wish here, keep in mind that your variable is $session_data[$session_name]['id'] = '2'; // also keep in mind all session variables are (string) type even (boolean) TRUE translates to '1' //or create new index $session_data[$session_name]['new_index'] = FALSE; // this retypes to (string) '0' //now put session in place $this->session->set_userdata($session_data); } if you like to use your own function add_data() you need to do this well you need to pass some data to it first add_data($arr = array(), $data = ''){} eg: array_unshift( $arr, $data ); { //your default array that is set to _initJSONSession() is just pure empty array(); $session_name = 'json'; $session_data[$session_name] = $this->_loadSession( $session_name ); // to demonstrate I use native PHP function instead of yours add_data() array_unshift( $session_data[$session_name], 'sample-data' ); $this->session->set_userdata( $session_data ); unset( $session_data ); } That is it.
You can add a "global" array per controller. At the top of your controller: public $notification_array = array(); Then to access it inside of different functions you would use: $this->notification_array; So if you want to add items to it, you could do: $this->notification_array['notification'] = "Something"; $this->notification_array['another'] = "Something Else";