Passing array form controller to other controller - php

One other question – in the user controller login method, after checking pressed button (login or forget password), in line : $data = $this->user_model->login(); return correct user information; "user name, family, user id" to be used in dashboard for using in log table and heAder of pages how to send this data to dashboard?
i tried to send it via redirect() but it fail
if ($this->form_validation->run() == TRUE) {
if (!empty($_POST['login'])) {
$data = $this->user_model->login();
if ($data != NULL)
{
redirect('dashboard');
} else {
redirect('user/login', 'refresh');
}
} elseif (!empty($_POST['forget'])) {
redirect('user/recover');
}
}
$this->data['subview'] = 'users/login';
$this->load->view('users/_layout_modal', $this->data);

Function redirect() doesn't save anything. You can try save $data to session by writing $this->session->set_userdata('some_name', $data);
Then you can call them with $this->session->userdata('some_name');
Note that $data can be object or array.
Assume that $data is array, then in dashboard you can use something like this:
$data = $this->session->userdata('some_name');
echo 'Username: '.$data['username'].'<br />';
echo 'Family: '.$data['family'];
...... so on ........

As per your question, you are validating the user login details and creating session for them.
Then store user information in session.
set session library auto-load in config/autoload.php. Then create session as below.
$this->session->set_userdata(
array(
"username"=>$username,
"user_id" => $user_id,
"family" => $family
)
);
In Dashboard:
You can access session with it's name:
echo $this->session->userdata("username");

Related

Codeigniter session ends after i close browser how to make remember checkbox

Codeigniter session ends after i close browser how to make remember checkbox ?
checkbox already in login form but i don't know how to do it ?
here's the login method in controller
public function login($page = 'login') {
if (!file_exists(APPPATH. '/views/main/' .$page. '.php')) {
// Whoops, we don't have a page for that!
show_404();
}
if($this->session->userdata('is_logged_in')) {
redirect('home');
$this ->session ->set_flashdata('alreadysignedin', '<div class="alert alert-info"><strong>Srroy !</strong> but you are already signed in.</div>');
} else {
$this ->load ->library('form_validation');
$data['title'] = ucfirst($page); // Capitalize the first letter
$this ->load ->model('users_model');
$this ->load ->view('include/header', $data);
$username = $this->input->post('username');
// Get User Role
$this->load->model('user_profile');
$this->user_profile->rolesdetail($username);
$userrole = $this->user_profile->rolesdetail($username);
// Get User Role </>
if ($this ->input ->post('login') AND $this->form_validation ->run('login') == TRUE) {
$data = array(
'id' => $userrole->id,
'username' => $this ->input ->post('username'),
'is_logged_in' => TRUE,
'roles' => $userrole->roles,
'email' => $userrole->email
);
$this ->session ->set_userdata($data);
$this ->session ->set_flashdata('logindone', '<div class="alert alert-success"><strong>Congratulation!</strong> you have logged in successfully.</div>');
redirect('home');
}
$this ->load ->view('main/'.$page, $data);
$this ->load ->view('include/footer', $data);
}
}
i read about cookies but i did not known how it works
It's simple, after submitting the form while verifying/processing the user credentials, if the checkbox value is found then create a cookie using $this->input->set_cookie(); after loading the cookie helper. Store the login info in that cookie and when the user arrives on login page check for that cookie and if data is present in that cookie just populate the form and its done. You can also keep the cookie data encrypted. check this link for further codeigniter cookies

display logged in user details from in codeigniter

view controller
<?php
class Site extends CI_Controller {
function homePage() {
$this->load->view('homePage');
}
function getValues($username) {
$this->load->model('customer_model');
$data['results']=$this->customer_model->getOne($username);
$this->load->view('view_db',$data);
}
}
I wanna display the logged in user details from database to a page. where the user logs in and it directs to home page and in that , there is link which directs to view the users details according to my design..
view Controller of login
<?php
class Login extends CI_Controller {
function index() {
//loads the main page to be displaye din the page
$this->load->view('login_form');
}
function validate_credentials() {
$this->load->model('customer_model');
$query = $this->customer_model->validate();
if ($query) {//if the user credidential is validated
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
//retrieving the session data
$this->session->set_userdata($data);
redirect('site/homePage');
} else {
$this->index();
}
}
the model view--- i have mentioned only getting a specific user
function getOne($username){
$query=$this->db->query('SELECT * FROM customer WHERE username = $username');
//$this->db->select('*');
//$query= $this->db->get('customer');
return $query->result();
}
and the view.. where now i just wanna retrieve the value and check later i can improve the interface ;)
<?php
//print_r($results);
foreach($results as $row) {
echo $row->id;
echo $row->last_name;
echo "<br/>";
}
?>
i know it should be done through a session .. but how to do it?
Ok so when this person who is now logged in clicks on the link that brings them to the getValues() method. You can just do a check to see if they are logged in, then if they are retrieve their information based on the sessions username key.
function getValues(){
if ($this->session->userdata('is_logged_in')) {
$username = $this->session->userdata('username');
//Get your db results
$this->load->model('customer_model');
$data['results']=$this->customer_model->getOne($username);
$this->load->view('view_db',$data);
} else{
//What you want to happen when they are not logged in.
}
Does that make sense?

Codeigniter form post and validation

I'm not a pro, but know my way around PHP, I'm new to Codeigniter.
Been going through these tutorials: http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-5-crud/
OK, so I have a page that lists users, clicking on users name will go to an edit page, the url of that page being: index.php/users/edit/1 (where 1 is the users id)
On edit page is a form, this form contains a few parts, each part is populated from different tables in the DB. So my Controller for edit is as follows:
function edit() {
//load model
$this->load->model('users_model');
//assign user data from DB
$data['data_user'] = $this->users_model->getUser($this->uri->segment(3));
//get users Password, using username from above
$data['data_user_password']= $this->users_model->getUserPassword($data['data_user'][0]->UserName);
$data['page_content'] = 'pages/users_edit';
$this->load->view('template/template', $data);
}
Notice:
$data['data_user'] contains users data like name, username, email
$data['data_user_password'] contains users password from a different table
I can then populate the form, on users_edit.php, this all works fine.
I'm accessing this data by doing the following:
if (is_array($data_user)) {
foreach($data_user as $user)
{
$userID = $user->id;
$userName = $user->Name;
$userUserName = $user->UserName;
$userMail = $user->Mail;
$userDepartment = $user->Department;
$userWorkPhone = $user->WorkPhone;
$userHomePhone = $user->HomePhone;
$userMobile = $user->Mobile;
}
}
//user password
if (is_array($data_user_password)) {
foreach($data_user_password as $user)
{
$userPassword = $user->value;
}
}
Name:
<?php echo form_input('name', set_value('name', $userName), 'id="name" class="inputLong"'); ?>
When I post, I'm sending data to: index.php/users/update
My controller for this page so far is:
function update() {
echo '<pre>';
print_r($_POST);
echo '</pre>';
//exit();
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('pages/users_edit');
}
else
{
$this->index();
}
}
For now, I'm just testing validation on users "name" where form input=name id=name
I think I'm not handling the if ($this->form_validation->run() == FALSE) part of it correctly, if the form contains data, it passes and redirects to index, if I leave name blank it either not handling the edit page correctly, or I dont know, something isnt right.. I think its because the page is being reloaded using the post array, and not passing the $data like I did in function edit().
Back to the form page, where it should be showing the validation_errors, its showing:
The Name field is required.
This is correct, however, for the rest of the fields that should be pre-populated, its showing PHP error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: userUserName
Filename: pages/users_edit.php
Line Number: 50
You could do your validation inside your edit function instead of having an update function, that way, your data is still available for your view and if the validation has errors, codeigniter will take in charge to repopulate your fields. If the validation is ok, you do your next step
function edit() {
//load model
$this->load->model('users_model');
//assign user data from DB
$data['data_user'] = $this->users_model->getUser($this->uri->segment(3));
//get users Password, using username from above
$data['data_user_password']= $this->users_model->getUserPassword($data['data_user'][0]->UserName);
$data['page_content'] = 'pages/users_edit';
$this->load->view('template/template', $data);
//is the form submitted
if(form submit){
if ($this->form_validation->run() == TRUE)
{
$this->index();
}
else
{
$this->load->view('pages/users_edit', $data);
}
}
}
$this->load->view('pages/users_edit');
Inside your function update(), after your validation you load view but you don't PASS any data variables to it. So you don't have any variables which you can access at your view file..
You have to set your variables the same way as in your function edit():
$this->load->view('template/template', $data);
Currently there is not set variable $data_user so you can't loop it and use it..

hashing/salting post data codeigniter

I am at the tail end of signing in a created user to an account. I've commented out my flow and everything seems to make since, however I am missing a step or two because now the post data password is not being hashed.
CONTROLLER:
function validate_credentials()
{
// WHEN THE VIEW IS LOADED THIS FUNCTION IS CALLED AND LOADS MODEL AS WELL AS DEFINES THE SALT VARIABLE AND LOADS THE ENCRYPTING HELPER LIBRARY
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
$salt = $this->_salt();
$this->load->library('encrypt');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->encrypt->sha1($user->salt. $this->encrypt->sha1($this->input->post('password')))
);
$user = $this->um->validate($data);
}
// IF ITS A REAL USER OPEN THE GATE AND LET THEM IN
if($user)
{
$this->session->set_userdata($data);
redirect('account/dashboard');
}
else
{
$this->index();
}
}
MODEL:
function validate($data)
{
$this->output->enable_profiler(TRUE);
// TAKING THE DATA FROM THE MODEL AND CHECKING IT AGAINST THE STORED INFO IN THE DB
$query = $this->db->where($data)->get('users', 1);
if($query->row())
{
return $query->row();
}
}
thanks in advance
$user->salt should just be $salt.

CakePHP passing id to edit form

I've noticed that their is many different ways to pass an ID to a form when editing a database entry. So for example for a edit user profile form I have the following code:
function edit($id = null)
{
$this->layout = 'page';
// this line isn't needed?
//$this->User->id = $id;
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your profile has been updated', 'flash', array('header' => 'Announcement', 'myclass' => 'success'));
$this->redirect(array('controller' => 'users', 'action' => 'view', $id));
}
}
}
Now the function expects an id passing in the url e.g. /users/edit/2 But let's say I wanted it to be something more user friendly like /profile/edit (rewrote by routing) I would no longer be passing in the ID as part of the url. As you can see in my code I have a line I have commented out because it isn't needed?
Also in the form I ALSO Need <?php echo $this->Form->input('id', array('type' => 'hidden')); ?> why?
Basically this is more of what are the options available to me to build various types of edit forms and passing data to the form. And what is the need for the hidden field in the form if the data is being passed either via the URL or some other way
I've also noticed on some sites that they have things like Form Keys and the username stored in meta tags in the page header???
EDIT:
public function beforeFilter()
{
$this->set('authUser', $this->Auth->user());
//
$user = $this->Auth->user();
if (!empty($user))
{
Configure::write('User', $user[$this->Auth->getModel()->alias]);
}
}
public function beforeRender()
{
$user = $this->Auth->user();
if (!empty($user))
{
$user = $user[$this->Auth->getModel()->alias];
}
$this->set(compact('user'));
}
// NEW VERSION
function settings()
{
$this->layout = 'page';
$this->set('title_for_layout', 'Edit Profile');
$this->User->id = $user['id'];
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your settings have been updated', 'flash', array('myclass' => 'success'));
$this->redirect(array('controller' => 'users', 'action' => 'settings'));
}
}
}
Also in the form I ALSO Need Form->input('id',
array('type' => 'hidden')); ?> why?
Having the id hidden in the form removes the need for your controller action to grab the $id from the uri (aka passed as parameter). When in the form, it will automatically be placed into your $data array.
what is the need for the hidden field
in the form if the data is being
passed either via the URL or some
other way
It's not needed in the form if it's available from the uri. You'd simply grab the $id and assign it to the User model (as the commented out code does).
let's say I wanted it to be something
more user friendly like /profile/edit
I assume that would be when the user is editing his own profile. In that case, your system should be able to retrieve the user's id via the session.

Categories