Value of member variable disappears in CodeIgniter/PHP - php

I have a situation of loosing value stored in $member variable.
class User extends CI_Controller {
protected $message;
function list()
{
$data['message'] = $this->message; // it's empty
$this->load->view('view', $data);
}
function delete($id)
{
$this->user_model->delete($id);
$this->message = "Success";
redirect('user/list');
}
}
The reason of using a redirect is to get a clean URL. I get empty value for $this->message in list() after getting redirected.
I even tried making it static, but still no luck.

You could try using flash messages:
function delete($id)
{
$this->user_model->delete($id);
$this->session->set_flashdata('message', 'Success');
redirect('user/list');
}
For this you are likely to need to load session library in constructor of you controller:
$this->load->library('session');
In your view use this:
<?php echo $this->session->flashdata('message');?>
You can preserve data in flash messages for several requests like this:
$this->session->keep_flashdata('message');
Have a look at this link

Related

CodeIgniter User is able to copy and paste URL and access main page

I am trying to build a simple login system using CodeIgniter. I have placed all of my functions into one controller and I have also placed a session check function called is_logged_in into the controller. However, the user can still copy and paste the URL once they have logged out and view the main page. It seems like my is logged in function isn't working. Am I missing something? It only works if I place a check in my header every time instead. Here is my code.
Controller file
function index()
{
$this->load->view('login');
}
function checklogin()
{
$this->load->model('user');
$query = $this->user->validate_login();
if($query)
{
redirect('portal/home');
}
else
{
$this->index();
}
}
function logout()
{
$this->session->unset_userdata('username');
$this->session->unset_userdata('is_logged_in');
$this->session->sess_destroy();
redirect($this->index(),'refresh');
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in)||$is_logged_in!=TRUE)
{
$this->index();
}
}
function home()
{
$this->is_logged_in();
$data['main_content'] = 'home';
$this->load->view('includes/template',$data);
}
function statements()
{
$this->is_logged_in();
$data['main_content'] = 'statements';
$this->load->view('includes/template',$data);
}
function about()
{
$this->is_logged_in();
$data['main_content'] = 'about';
$this->load->view('includes/template',$data);
}
}
?>
This is what I place into my headers that actually works instead of the function
<?php
if(!$this->session->userdata('is_logged_in'))
{
redirect('portal/index');
}
?>
User Model
<?php
class User extends CI_Model{
function __construct()
{
parent::__construct();
}
public function validate_login()
{
//$this->form_validation->set_rules('username', 'Username', 'trim|required');
//$this->form_validation->set_rules('password', 'Password', 'trim|required');
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean(md5($this->input->post('password')));
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('accounts');
if($query->num_rows()==1)
{
foreach($query->result() as $row)
{
$sess_data = array(
'username'=>$this->input->post('username'),
'is_logged_in'=>TRUE,
'privilege'=>$row->privilege
);
}
$this->session->set_userdata($sess_data);
return true;
}
else
{
// echo $password;
}
}
}
?>
Also, how can I combine the commented out part in the user model with the next lines? I want an error message to be sent if no input is placed. Hope I can get help with this.
So much wrong in this. Do not, not ever, use a single controller for your application. Things will get pretty big, pretty fast, and then you have one unreadable blob of a file. Keep your application code normalized. That's why you are using MVC. If you then need a method accessible from every, or nearly every controller, then put this function into a base controller(MY_Controller i.e.), or a model, or a library, depending on the functionality of this method. But in your case, this is for a base controller. This wont help with your problem, but just a friendly suggestion.
The problem with your code is, the visitor hits the URL for method "statements" and this is what happens:
statements calls is_logged_in
is_logged_in determines user is not logged in and calls index
index loads the login view
statements method loads the statements view
After you check for log in, and determine that the user is not logged in, you have to prevent further execution of other parts of your code. I would suggest having is_logged_in method returning a bool(false) value, and the statements(and other methods) then stopping execution. But if you would separate your code like you should over multiple controllers, then maybe have the is_logged_in controller to redirect the user to the login page.

Why codeigniter not showing the variable sent from controller to view?

I want to send a variable '$msg_notf' from my controller to my view but every time I do this, codeigniter returns the error "Undefined variable: msg_notf" .
My Controller,
public function send_message(){
$this->load->model('model_student');
$msg_send=$this->model_student->send_message($this->session->userdata('roll_no'));
if($msg_send==true){
$result['msg_notf']='message sent';
$this->load->helper('url');
redirect('http://localhost/CheckIn_System/index.php/student',$result);
}else{
$result['msg_notf']='unable to send message';
$this->load->helper('url');
redirect('http://localhost/CheckIn_System/index.php/student',$result);
}
}
In view,
echo $msg_notf;
In Controller
public function __construct()
{
parent::__construct();
$this->load->helper('url');//load once Controller load
}
public function send_message()
{
$this->load->model('model_student');
$msg_send=$this->model_student->send_message($this->session->userdata('roll_no'));
if($msg_send==true){
$result['msg_notf']='message sent';
$this->load->view('student',$result);//passing data to view
}else{
$result['msg_notf']='unable to send message';
$this->load->view('student',$result);//passing data to view
}
}
in view
foreach ($msg_notf as $new_msg_notf)
{
echo $new_msg_notf['your_data_field'];//showing your data
}
Your controller may look like this :
public function __construct(){
parent:: __construct();
$this->load->helper('url');
}
public function send_message(){
$this->load->model('model_student');
$msg_send=$this->model_student->send_message($this->session->userdata('roll_no'));
if($msg_send==true){
$result['msg_notf']='message sent';
$this->load->view('path', $result); // path of the
http://localhost/CheckIn_System/index.php/student
}else{
$result['msg_notf']='unable to send message';
$this->load->view('path',$result);
}
}
If you want use redirect, the best idea is use Flashdata. Is a one-time session var that persists until you use it, then is deleted.
you need call: $this->load->library('session');
Declaration:
$this->session->set_flashdata('item', 'value');
To read:
$this->session->flashdata('item');
https://ellislab.com/codeigniter/user-guide/helpers/url_helper.html
The redirect() function does a "header redirect" to the URI specified. The optional second parameter allows you to choose between the "location" method (default) or the "refresh" method.
If you want to pass data into a view use
$this->load->view("View_file", $result);
and on the view page access it like
echo $msg_notf;
With redirect function you should use Session (Userdata or Flashdata)
Flashdata is preferred in this case.

codeigniter - pass messages to view

I am new to codeigniter. I have a controller users which loads a login view.
class user extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form'));
}
public function login()
{
$this->load->model('user_images');
$data = $this->load->model('login');
$this->load->view('login', $data);
}
}
In the login model I handle all the validation and processing. If there is a validation error or the like I return $data['msg'] = 'some error message'; I pass this data via $data = $this->load->model('login'); to $this->load->view('login', $data); and in view I echo $msg. However upon submission the form processes, if I enter the correct credentials I get logged in, however if I enter some wrong credentials the validation errors do not get passed to the view. I am moving this project over from an non-framework environment, so I am sure that the validation rules work .etc. I am just not sure why the messages are not getting parsed on the view.
It looks like you are getting this wrong
$data = $this->load->model('login');
The load->model() loads the login_model and makes it methods available via
$this->login->youMethodHere().
f there is a validation error or the like I return $data['msg'] = 'some error message'; I pass this data via $data = $this->load->model('login'); to $this->load->view('login', $data);
When you return something from a method/function you do not return the variable. You return the value of the variable.
You should add you method to the login_model (perhaps this should be user_model...) and return ex. an array or mysqli result set from the model. Depeanding on what the models returns you should set the data.
$this->load->model('user_model');
$login_succes = $this->user_model->login($username, $password);
if( $login_success )
{
$data['msg'] = 'hurrah you did it
...

how to call a function in another controller in code igniter?

I want to call a function in another controller. for example if user try to log in with incorrect parameter then the application will redirect to another controller and passing a variable (array).
class User extends Controller {
function User()
{
parent::Controller();
}
function doLogin()
{
$userData = $this->users->getAuthUserData($user,$password);
if(empty($userData)){
// this is where i need to call a function from another controller
}else{
echo 'logged in';
}
}
}
is it possible passing a variable using redirect() function in url helper?
Yes you can use redirect('othercontroller/function/'.url_encode($data), 'location');
That should work.
edit: you could also put the code in a helper.
<?php
$array = array('foo'=>'bar', 'baz'=>'fubar', 'bar' => 'fuzz');
$json = json_encode($array);
$encoded_json= urlencode($json);
/* now pass this variable to your URL redirect)
/* on your receiving page:*/
$decoded_json= urldecode($encoded_json);
/* convert JSON string to an array and output it */
print_r(json_decode($decoded_json, true));
?>
this code:
takes an array, converts it to a JSON encoded string.
we then encode the $json string using url_encode. You can pass this via the url.
Decode this URL, then decode the JSON object as an associative array.
might be worth a try
If you want to call a function of one controller from another controller then you can use redirect Helper.
For example:
class Logout extends CI_Controller {
function index() {
session_destroy();
redirect('index.php/home/', 'refresh');
}
}
it will call another contoller.

URL segment - User Profiles - Codeigniter

I'm trying to create user profiles for my site where the URL is something like
mysite.com/user/ChrisSalij
Currently my controller looks like so:
<?php
class User extends Controller {
function user(){
parent::Controller();
}
function index(){
$data['username'] = $this->uri->segment(2);
if($data['username'] == FALSE) {
/*load default profile page*/
} else {
/*access the database and get info for $data['username']*/
/*Load profile page with said info*/
}//End of Else
}//End of function
}//End of Class
?>
At the moment I'm getting a 404 error whenever i go to;
mysite.com/user/ChrisSalij
I think this is because it is expecting there to be a method called ChrisSalij.
Though I'm sure I'm misusing the $this->uri->segment(); command too
Any help would be appreciated.
Thanks
It's because the controller is looking for a function called ChrisSalij.
A few ways to solve this:
change
function index(){
$data['username'] = $this->uri->segment(2);
to be
function index($username){
$data['username'] = $username;
and use the URL of mysite.com/user/index/ChrisSalij
if you don't like the idea of the index being in the URL you could change the function to be called a profile or the like, or look into using routing
and use something along the lines of
$route['user/(:any)'] = "user/index/$1";
to correctly map the URL of mysite.com/user/ChrisSalij

Categories