Session in Code Igniter - php

I want to ask this question if how can we make a session in code igniter specially in logging in and logging out on the account. I want to know the step by step following the MVC of code igniter.

At the login time after executing query set session data in set_userdata function and passing data array whos you want to set.
$this->session->set_userdata('session data here');
And at the time of logout you have to call unset_userdata function and passing array of array whos you have to set at login time.
$this->session->unset_userdata('session data here');

using my code as an example you can do this i have a controller called iris.php and a model called script.php. i use the iris to call and make use of the script model.
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}
public function index()
{ $this->load->view('index');
}
public function login_in()
{
$login = $this->script->check_login();
if($login->num_rows() == 1){
foreach ($login->result_array() as $row) {
$newdata = array(
'fullname' => $row['fullname'],
'email' => $row['email'],
'member_id' => $row['member_id'],
'transtatus'=>$row['transtatus']
);
$this->session->set_userdata($newdata);
}
redirect('iris/user_home');
}else
{
$data = array('alert'=>$this->alert->log_alert());
$this->load->view('common/header');
$this->load->view('login',$data);
$this->load->view('common/footer');
}
}`
i first load the model script model under the constructor and in the login function of the iris controller i called the function in the script $login=$this->script->check_login();
in the script.php we have the following code.
{public function check_login(){
$email = $this->input->post('email');
$password = $this->input->post('password');
$query = "SELECT * FROM `iris_user`
WHERE`email`=? AND`password`= ? ";
$result = $this->db->query($query, array($email, $password));
return $result;
}
remember you have to have loader the session class helper form the application/config/autoload.php file in the CIfolder
$autoload['libraries'] = array('database', 'session');
the session is alway start once it has been autoloaded, but can be destroyed when maybe creating a logout function.
also note when adding to the session data variable to access the session variable you will have to use the name that was used when declaring the session variable. e.g to access the fullname you would do this in code
echo $_SESSION['fullname'];

In the controller load library session :
$this->load->library('session');
Use below sentence for session create :
$this->session->set_userdata("session_name",session_value);
For Session Unset:
$this->session->unset_userdata("session_name");

Related

cannot access object user from another php page

I'm trying to learn MVC pattern but,even if I'm trying hard, it seems I still got big issues.
I have got a controller,named baseController that do the following:
class baseController {
public $model;
public $user;
...
$activeuser = $this->model->getlogin();
if ($activeuser != 'invalid user' && $activeuser != "") {
$this->user=$activeuser;
header("Location:home.php");
}
I have got a model.php file which contains the getlogin() function:
public function getlogin() {
if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
$username = mysql_real_escape_string($_REQUEST['username']);
$pwd = mysql_real_escape_string($_REQUEST['password']);
$pwd = md5($pwd);
$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password ='$pwd' AND attivato =1;");
if (mysql_num_rows($query) == 1) {
require_once 'User.php';
$sql=mysql_fetch_array($query);
$activeuser = new User();
$activeuser->username=$sql['username'];
$activeuser->email=$sql['email'];
return $activeuser;
} else {
return 'invalid user'; //TO-DO
}
}
}
The home.php create a new homeController and calls its invoke() function.The homeController file include the view page,that's called afterlogin.php.
In the afterlogin.php I've got the "ERROR":
if (isset($activeuser)){
echo "<p>Utente ".$activeuser->username."</p>";
echo "<p>Email ".$activeuser->email."</p>";}
//echo "<p>Pass ".$activeuser->pwd."</p>";
echo"<h1> HOMEPAGE, LOGIN OK </h1>";
It seems the homeController,and so the afterlogin page cannot access the user created in the baseController file. If I try an echo inside the baseController of $this->user->username everything is working. What should I do?? HELP!!
The client-server lifecycle is effectively stateless; on every page load, your variables and objects are wiped out.
There are the client-sourced $_POST and $_GET superglobals, which is part of the standard form submission and url query processes.
The server has databases, file writing (sketchy from a security POV) and the $_SESSION superglobal. These are the ways the server can manage a data state between pageloads.
Understand that if you're using objects, you need to have them instantiated on every page load for them to work. You can store your user_ID in $_SESSION['user_ID'] and instantiate the user object from it every time, making appropriate changes according to how the data changes.

Changing content when user has logged in i.e. when session starts

How do I change the content for a user when he logs in? I mean like enabling voting, changing "login" to "logout" etc.
What I think to do is to start the session when user logs in (I am preferring to start session only when user logs in, not all the time). Then add data to the session's cookie like-
//controller
$moredata = array(
'username' => $this->username,
'login' => TRUE
);
$this->session->set_userdata($modedata);
//redirect
Then in the other controller, where he has been redirected I check the following-
$login = $this->session->userdata('login');
if ($login==TRUE)
Depending on the 'if' condition I will pass a variable to the view, with the help of that variable I will forward only the div/sections which should be shown to a logged-in user.
The problem is, while performing the above comparison Codeigniter shows following error (remember I haven't added 'session' in autoload array yet)
Message: Undefined property: NameOfController::$session
And If I set following in the autoload file
$autoload['libraries'] = array('session');
then the "if ($login==TRUE)" comparison always shows FALSE.
What should I do?
If I were you, I'd place all your session checks in a base controller which all your other main controllers extend. This allows you to keep things DRY:
class BaseController extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
// Will return true or false
return $this->session->userdata('login');
}
}
And in one of your functional controllers (the example below handles users):
class UserController extends BaseController {
public function __construct()
{
parent::__construct();
}
public function profile()
{
// Redirect if not logged in
if (!$this->isLoggedIn()) {
$this->redirect('some/other/page')
}
}
public function register()
{
// Show different HTML if not logged in
$data = array(
'isLoggedIn' => $this->isLoggedIn()
);
$this->load->view('register', $data);
}
}
The second method in UserController allows you to render different content in your view:
<? if ($isLoggedIn): ?>
<p>You're logged in!</p>
<? else: ?>
<p>Not logged in</p>
<? endif; ?>
On my last project we created a simple permissions helper that had functions to check for logged-in status and for privilege levels. Then we'd just call the helper's functions as needed from anywhere in the system. If the user is logged in and has privs for that content then they get the content - otherwise we'd redirect them to a registration or other error page. Since all of that logic is in the helper functions, we could wrap any permission-requiring code in a quick permissions call like if(is_logged_in()){code requiring login to access}.

How to save values in session?

I am working with cakephp.Recently I am facing problem in saving data in session.
I have created login page which will send value to controller/action. it will receives like this.
function ajaxCall() {
$this->autoRender = false;
$this->layout = 'ajax';
$arrData = $this->params['url'];
if(!empty($arrData)){
if($arrData['submit']=='Y'){
$userObj = new Api(); // create an instance of the user class
$userInfo = $userObj->login($arrData['email'],$arrData['password']); // call the api login user methods
$xml = simplexml_load_string($userInfo);
$userId = $xml->message->id;
if($userId != "0" && $userId != ""){
$this->setCurrentUserId($userId);
echo "success";
}
else{
echo "no";
}
}
}
}
public function setCurrentUserId($userId)
{
//Is session alive
//if not then redirect to session time out page
//session_start();
//session_register("");
if($userId == 419 || $userId == 423){
$userId1 = $this->Session->write('userId', $userId);
}else{
$userId1 = $this->Session->write('userId', $userId);
}
return $userId1;
}
my controller contain also these line to include helpers,component
public $components = array('Session');
public $helpers = array('Html','Session');
and in core.php file i set session as-
Configure::write('Session', array(
'defaults' => 'php', 'ini' => array('session.auto_start' => 1)
));
Please help me as i am unable to save userId in session
Thanks
On the internet there You can find CakePHP cookbook to create simple application with authentication and authorization: book.cakephp.org
Here You can find very simple example on how to create UsersController, User model and Views for login etc with login action using CakePHP's inbuilt Auth object - there is no need to write the whole login logic - Auth object will do most for You.
Hope You'll enjoy it!

MVC INSERT INTO Stuck with Where to go from here

I have a model register.php (under app/model/register.php)
<?PHP
// Load the [default] db group
$this->load->database();
// Get Input from init form, sanitize, plop into variables.
class Register extends Model{
function formModel(){
//load parent constructor
parent::Model();
}
function sanitizeInput(){
var $name = mysql_real_escape_string($_POST['fullname']);
var $email = mysql_real_escape_string($_POST['email']);
var $pass = mysql_real_escape_string($_POST['password']);
var $dySalt = mt_rand(20,100);
var $pass = hash('sha512',$dySalt.$pass);
}
// Set form variables into object; define db table
$registeredObject = new getSanitizeNewRegistrant();
$tbl = 'Fan';
function SendRequestForData(){
if{
$this->db->insert($tbl,$object);
// .. redirect()
echo "Sent";
}
else{
echo "Oops, could not register you";
}
}
}
?>
I'm loading this model into a controller registerUsers.php (under app/controller/registerUsers.php)
<?PHP
$this->load->model('register'),'', TRUE);
?>
I'm confused how I go about implementing this in a view from here?
The MVC framework works as follows:
Model interacts with the database:
Here is where you want to put all of your functions that do nothing more than insert and return data to/from the database.
Views are what the user sees:
Here is where you'll have your html pages that make use of the data you got through your model
Controllers simply connect the two:
The controller preps data, uses the model to interact with the database, and loads the views for the user to see
If you had a function registerUser() in your register model, you would do something like this to actually use it within a function in the controller:
$this->load->model( 'register' ); // Load register model
$return = $this->register->registerUser( $_POST['username'], $_POST['email'], $_POST['password'] ); // Try to register the user to the database
if( $return === "TRUE" ) {
$this->load->view( 'success' ); // Hooray!
}
else {
$this->load->view( 'fail' ); // :(
}
Here, the controller loads the register model, tries to save the username, email and password using the registerUser() function within the model, and loads the correct view accordingly.
Obviously you'll want to clean $_POST data and everything before writing it to the database. This should be done within the controller.

Is there an easy way to get AuthComponent user data from a view in CakePHP?

According to the cakebook section on the Auth component, I can implement simple authentication by using the following Users controller:
class UsersController extends AppController {
var $name = 'Users';
var $components = array('Auth'); // Not necessary if declared in your app controller
/**
* The AuthComponent provides the needed functionality
* for login, so you can leave this function blank.
*/
function login() {
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
I would like to be able to something like the following into my view:
<?php
$username = $auth->user('username');
echo "Welcome " . $username;
?>
Is there a simple way to do this, or do I need to overwrite the login function and store the username to the session?
Update
Alexander's answer is exactly what I wanted. However, I will add the following in case someone else gets confused like I did.
It took me a while to understand that if you change the model that Auth uses (for example, you might have a 'persons' table instead of 'users'), then you need to use something like:
$persondata = $session->read('Auth.Person');
Actually this information is easily available from the session. You use the session helper to grab it. I believe the correct syntax is :
$userdata = $session->read('Auth.User');
$username = $session->read('Auth.User.username');
EDIT:
For CakePHP 2.X and on the syntax is:
$userdata = $this->session->read('Auth.User');
$username = $this->session->read('Auth.User.username');
Check out AuthComponent-Methods in the CakePHP manual....
You can access an user info after a user has logged in from the session via $this->Auth->User(). So if you want the username, just use this in the controller.
$this->set('username', $this->Auth->User('username'));
You can now use $username in the view.
Add a method in your AppController
function beforeFilter() {
$ath = $this->Auth->user();
$this->set('userDetails', $ath['User']);
}
And then you can access it from your views and/or layouts via $userDetails
To access Auth vars in views just do it:
echo $session->read('Auth.User.id');

Categories