How to save values in session? - php

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!

Related

Session in Code Igniter

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");

What causes the session to be recreated or to be gone after a page refresh?

I am using codeigniter on my project, and I have a login module and I authenticate each module. When the session does not exist then redirect to the login page. So, this works but sometimes it may happen when I login and then refresh the page I get redirected to the login page (meaning the session is gone).
Please do not try to tell me to use another library such as php native etc. I just want to know what the problem causing this is.
function _admin_login()
{
$this->form_validation->set_rules($this->login_rules);
$data['title'] = "Login";
$data['form_url'] = $this->uri->uri_string();
$data['login_btn'] = form_submit('login','Sign In','class="btn btn-large btn-block btn-primary"');
if($this->form_validation->run($this) == FALSE){
$data['user'] = form_input('username','','class="input-block-level input-large" placeholder="Username"');
$data['passw'] = form_password('password','','class="input-block-level input-large" placeholder="Password"');
$this->template->set('title','Login');
$this->template->load('template_login','login_view',$data);
}else{
$username = $this->input->post('username',true);
$row = $this->authentication_model->get_user_info($username);
$this->session->set_userdata('user',$row['user_id']);
$this->session->set_userdata('username',$row['username']);
$this->session->set_userdata('login_state',true);
$this->authentication_model->update_last_login();
redirect('product');
}
}
This is my login script, if the validation passes then the session is set... and in every controller I have checked the session script. Example below:
$this->authentication_plugin->check_logged_in();
function check_logged_in()
{
if(logged_in() === FALSE){
set_alert('Login in to view this page!!','error');
set_bookmark('login_url');
redirect("login");
}
}
function logged_in()
{
$CI =& get_instance();
$user = $CI->session->userdata('user');
if(!$CI->load->library('session')){
echo "no session is loaded";
die;
}
if(!empty($user)){
return true;
}else{
return false;
}
}
Any ideas? Thanks!
autoload the session library and remove that from your login script.
In config/autoload.php look for $autoload['libraries']
add 'session'
in config/config.php
scroll down to cookie configs and look for $config['sess_cookie_name']
make sure there is no underscore in the cookie name. you have to change the codeigniter default name to do this.
test by doing session checks in the constructor. its a quick sanity check to see if the sessions are working or not.

How to store and change Zend_Auth session ID?

I've recently started using Zend Framework and I'm still pretty used to session_start, and assigning variables to certain session names (ie: $_SESSION['username'] == $username)
I'm trying to figure out how to do something similar to this in Zend. Right now, my auth script checks the credentials using LDAP against my AD server and, if successful, authenticates the user.
I want to create a script that will allow an admin user to easily "enter" someone else's session. Let's say admin1 had an active session and wanted to switch into user1's session. Normally I would just change the $_SESSION['username'] variable and effectively change the identity of the user logged in.
But with Zend, I'm not quite sure how to change the session info. For what it's worth, here's my authentication script:
class LoginController extends Zend_Controller_Action
{
public function getForm()
{
return new LoginForm(array(
'action' => '/login/process',
'method' => 'post',
));
}
public function getAuthAdapter(array $params)
{
$username = $params['username'];
$password = $params['password'];
$auth = Zend_Auth::getInstance();
require_once 'Zend/Config/Ini.php';
$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');
$log_path = $config->ldap->log_path;
$options = $config->ldap->toArray();
unset($options['log_path']);
require_once 'Zend/Auth/Adapter/Ldap.php';
$adapter = new Zend_Auth_Adapter_Ldap($options, $username, $password);
$result = $auth->authenticate($adapter);
if ($log_path) {
$messages = $result->getMessages();
require_once 'Zend/Log.php';
require_once 'Zend/Log/Writer/Stream.php';
require_once 'Zend/Log/Filter/Priority.php';
$logger = new Zend_Log();
$logger->addWriter(new Zend_Log_Writer_Stream($log_path));
$filter = new Zend_Log_Filter_Priority(Zend_Log::DEBUG);
$logger->addFilter($filter);
foreach ($messages as $i => $message) {
if ($i-- > 1) { // $messages[2] and up are log messages
$message = str_replace("\n", "\n ", $message);
$logger->log("Ldap: $i: $message", Zend_Log::DEBUG);
}
}
}
return $adapter;
}
public function preDispatch()
{
if (Zend_Auth::getInstance()->hasIdentity()) {
// If the user is logged in, we don't want to show the login form;
// however, the logout action should still be available
if ('logout' != $this->getRequest()->getActionName()) {
$this->_helper->redirector('index', 'index');
}
} else {
// If they aren't, they can't logout, so that action should
// redirect to the login form
if ('logout' == $this->getRequest()->getActionName()) {
$this->_helper->redirector('index');
}
}
}
public function indexAction()
{
$this->view->form = $this->getForm();
}
public function processAction()
{
$request = $this->getRequest();
// Check if we have a POST request
if (!$request->isPost()) {
return $this->_helper->redirector('index');
}
// Get our form and validate it
$form = $this->getForm();
if (!$form->isValid($request->getPost())) {
// Invalid entries
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}
// Get our authentication adapter and check credentials
$adapter = $this->getAuthAdapter($form->getValues());
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
// Invalid credentials
$form->setDescription('Invalid credentials provided');
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}
// We're authenticated! Redirect to the home page
$this->_helper->redirector('index', 'index');
}
public function logoutAction()
{
Zend_Auth::getInstance()->clearIdentity();
$this->_helper->redirector('index'); // back to login page
}
}
Is there any way to do what I have described? Thanks for any suggestions.
Given your code, the result of authenticating is stored in the PHP session through a Zend_Auth_Storage_Session object.
Calling Zend_Auth::getIdentity() gets access to the storage and returns the result if it is not empty. Likewise, you can change the stored identity by getting access to the underlying storage and changing its value. The actual identity stored as a result of authenticating with Zend_Auth_Adapter_Ldap is just a string value representing the LDAP username.
To effectively change the logged in user, you can do:
Zend_Auth::getInstance()->getStorage()->write('newUserName');
This assumes the default behavior which should be in place given your code.
What I do in my applications after successful authentication is to create a new object of some User model, and write that to the Zend_Auth session so that I have more information about the user available in each session, so you should be aware that different things can be in the storage depending on the application.
This is what I do for example:
$auth = new Zend_Auth(...);
$authResult = $auth->authenticate();
if ($authResult->isValid() == true) {
$userobj = new Application_Model_UserSession();
// populate $userobj with much information about the user
$auth->getStorage()->write($userobj);
}
Now anywhere in my application I call Zend_Auth::getInstance()->getIdentity() I get back the Application_Model_UserSession object rather than a string; but I digress.
The information that should help you is:
$user = Zend_Auth::getInstance()->getIdentity(); // reads from auth->getStorage()
Zend_Auth::getInstance()->getStorage()->write($newUser);

How to set the timeout while using Zend_auth in Zend framework

I am using Zend_auth for authentication purposes.Code for the same is as follows:
$authAdapter = $this->getAuthAdapter();
$authAdapter->setIdentity($username)
->setCredential($password);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
# is the user a valid one?
if ($result->isValid()) {
# all info about this user from the login table
# ommit only the password, we don't need that
$userInfo = $authAdapter->getResultRowObject(null, 'password');
# the default storage is a session with namespace Zend_Auth
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);
$emp_id = $userInfo->employee_id;
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$array_db = new Application_Model_SetMstDb();
$array_name = $array_db->getName($emp_id);
foreach ($array_name as $name) :
$fname = $name['first_name'];
$lname = $name['last_name'];
endforeach;
$firstname = new stdClass;
$lastname = new stdClass;
$userInfo->firstname = $fname;
$userInfo->lastname = $lname;
$privilege_id = $userInfo->privilege_id;
echo 'privilege in Login: ' . $privilege_id;
$this->_redirect('index/index');
} else {
$errorMessage = "Invalid username or password";
$this->view->error = $errorMessage;
}
where getAuthAdapter() as follows:
protected function getAuthAdapter() {
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('credentials')
->setIdentityColumn('employee_id')
->setCredentialColumn('password');
return $authAdapter;
}
I want to set a session timeout.I want to set a timeout of 5 mins and when user does not being active for 5 mins then session should be expired that is logout action should be called whose code is as follows:
public function logoutAction() {
// action body
Zend_Auth::getInstance()->clearIdentity();
$this->_redirect('login/index');
}
Thanks in advance.Plz Help me.Its urgent.
When I use
$session = new Zend_Session_Namespace( 'Zend_Auth' );
$session->setExpirationSeconds( 60 );
control redirects to login page automatically after 60 seconds but I want that if the user of the application in inactive for 60 seconds then only it redirects.At present whether user is active or not redirection occurs.
I wouldn't use init() for this. init() should be use to set object state.
I would use preDispatch(). But to avoid using it all controllers or making a base controller and then extending. You could do a plugin and add it on the Bootstrap.
class YourControllerPlugin extends Zend_Controller_Plugin_Abstract {
public function preDispatch() {
//check if expired
if(hasExpired()) {
//logout and redirect
}
}
}
to add it on Bootstrap :
public function __initYourPlugin () {
$this->bootstrap('frontController');
$plugin = new YourControllerPlugin();
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin($plugin);
return $plugin;
}
I'm looking at my code for this right now. This snippet is from a front controller plugin. Each time an authenticated user requests a page, I reset their session expiration so they've got 60mins from they were last "active".
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
//check whether the client is authenticated
if (Zend_Auth::getInstance()->hasIdentity()) {
$session = $this->_getAuthSession();
//update session expiry date to 60mins from NOW
$session->setExpirationSeconds(60*60);
return;
}
Aside: I'm looking over this code for a way to show the user a "your session has expired" message rather than the current "you're not authenticated" message.

Share session between 2 websites: a legacy PHP and a Kohana 3.1 site

I have 2 php websites in the same machine. The first site (a legacy system) has a basic auth: checks if is set $_SESSION['user_id']. I'm working in the second site (a Kohana 3.1 based) that will extends the funcionalities of the first one.
Both sites will link each other, so I need to share the session between those systems. Both sites use the same Database. Users will login in the first site.
In my site I have a code that detects the $_SESSION['user_id'] of the first one, but I'm having problems retaining the session with the Kohana-Auth module.
The first site (the legacy one) checks the session like this:
<?php
session_start();
if(empty($_SESSION['user_id']))header("Location: index.php?action=3");
... //more dark code
this is in all php files... a lot of files.
In my Kohana site I have a controller that before any action checks the session.
<?php
class My_Controller extends Controller_Template {
public function before() {
session_start();
$this->auth = Auth::instance();
if ($this->auth->logged_in()) {
//I have session in the second site... Do I have a session on the first one?
if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] == "") {
//I have no session in the first site... I logout the user in my site
$controller = Request::current()->controller();
if ($controller != 'auth') {
Request::current()->redirect('auth/logout');
}
}
$this->user = ORM::factory('user', $this->auth->get_user()->id);
} else {
//I have no session in the second site... Do I have a session on the first one?
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
if (isset($user_id)) {
$user = Model_User::get_user($user_id);
if ($user->loaded()) {
//I have session in the first site... I login the user in my site
$this->auth->force_login($user);
$this->user = ORM::factory('user', $this->auth->get_user()->id);
}
}
if (!$this->auth->logged_in()) {
//I still have no session => redirect to login of the first site
//Request::current()->redirect(...);
echo Debug::vars("BUUUU");
}
}
}
}
This code is near to work: I can go from one site to the other and the user is detected... but I realised that when the user navegates between the differents actions inside my Kohana site, the "logins" couter of the Users table increases.
That means that before any action the "$this->auth->logged_in()" is FALSE... and this means that the Auth module do not retains my user between actions and do the force-login every time.
I don't know what can I do.
I want detect the session form the first site, but I don't want to login this user in every click.
I found the answer!!
In Kohana 3.1, the Kohana_Session class has a default value of the cookie.
/**
* #var string cookie name
*/
protected $_name = 'session';
That value didn't match with the default name of the PHP session: "PHPSESSID".
And that value is modified by creating a config file called "session.php" in the config directory. So I created a config/session.php like this:
<?php defined('SYSPATH') or die('No direct script access.');
return array(
'native' => array(
'name' => 'PHPSESSID',
)
);
And my final controller was something like this:
<?php
class My_Controller extends Controller_Template {
public function before() {
$this->auth = Auth::instance();
if ($this->auth->logged_in()) {
//I have session in the second site... Do I have a session on the first one?
$user_id = Session::instance()->get('user_id');
if (!isset($user_id) || $user_id == "") {
//I have no session in the first site... I logout the user in my site
$controller = Request::current()->controller();
if ($controller != 'auth') {
Request::current()->redirect('auth/logout');
}
}
$this->user = ORM::factory('user', $this->auth->get_user()->id);
} else {
//I have no session in the second site... Do I have a session on the first one?
$user_id = Session::instance()->get('user_id');
if (isset($user_id) && $user_id != "") {
$user = Model_User::get_user($user_id);
if ($user->loaded()) {
//I have session in the first site... I login the user in my site
$this->auth->force_login($user);
$this->user = ORM::factory('user', $this->auth->get_user()->id);
}
}
if (!$this->auth->logged_in()) {
//I still have no session => redirect to login of the first site
//Request::current()->redirect(...);
echo Debug::vars("BUUUU");
}
}
}
}
that's all...

Categories