I want something like this in a class structure:
$public $choice;
function __construct(){
$this->set_login($this->choice);
}
private function set_login($this->choice){
if($this->choice=='2'){
// don't set login credentials
}else{
// set login credentials
}
}
The above code requires $choice to be set every time before I initialize the class.
But I want to set $choice as optional parameter.
I want if in any page, I call like this:
$login = new login();
that class will set login credentials normally but if called like this:
$login = new login();
$login->choice = 2;
then login credentials will not be set.
I am not sure, whether the class will be executed in such way because as soon as I initialize the class, the __construct method will be called and the $choice to be set at that time. But if I set $choice after initialization, then will the code work?
How can I make a parameter optional in oop?
Just define you method set_login as:
public function set_login($choice = 1) {
if ($choice == 2) {
// don't set login credentials
} else {
// set login credentials
}
}
And use it like that:
$login = new login();
// Login.
$login->set_login();
// Doesn't login.
$login->set_login(2);
EDIT:
Another solution:
private $choice;
function __construct($choice = false) {
$this->set_login($choice);
// If you want to remember the choice, you can save it in a property:
$this->choice = $choice;
}
private function set_login($choice) {
if ($choice == 2) {
// don't set login credentials
} else {
// set login credentials
}
}
Note that the following code will never work as you expect because you change the value of choice after executing the method set_login in the constructor:
$login = new login();
$login->choice = 2;
Related
i have a normal php login which connects to a database authenticates the user, now i need to convert this to a login that uses yii framework, can anybody tell me in order to do so.. what are the first things that i should do and can i convert this to yii login. following is the current login function that i have to call
function login($usr,$pwd) {
$query = "SELECT * FROM login WHERE us.username='$usr' AND us.password='$pwd'; ";
$dataReader=$command->query();
$row = mysql_fetch_array($dataReader);
$log = new stdClass();
if($row) {
$pro->accountID = (int)$row['accountID'];
$pro->accountname = $row['accountname'];
$pro->usertype = (int)$row['usertype'];
$string = rand() . 'SURVAYLAND' . rand() . $usr. $pwd;
$_SESSION['SURVEY_AUTHENTICATE_KEY'] = md5($string);
} else {
$pro = false;
}
}
Whenever you call Yii::app()->user, you get an instance of CWebUser. This is the way Yii represents the user that it currently viewing your application.
This user can be logged in or access the app without login (in other words, be a guest).
Class CWebUser has a method called login, which, as you expected, logs in a user.
Method login() takes as argument an object that implements IUserIdentity interface.
The easiest way to make your own is to create a simple class (call it MyIdentity for exemple):
//this class' constructor takes a username and a password
class MyIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
// check username and password in DB
// return true or false to signal whether user should be logged in
}
public function getId()
{
return $this->_id;
}
}
Then use what you just created to actually log in an user:
// Login a user with the provided username and password.
$identity=new MyIdentity($username,$password);
if($identity->authenticate())
Yii::app()->user->login($identity);
else
echo $identity->errorMessage;
i'm calling name from database using $_SESSION['name']; after using this i'm getting this Notice: Undefined index: name in C:\Users\..\logged_in.php on line 2 can you tell me what's goin on? please help please...
logged-in.php
Hey, <?php echo $_SESSION['name']; ?>. You are logged in.
Try to close this browser tab and open it again. Still logged in! ;)
Logout
login.php
<?php
/**
* Class login
* handles the user's login and logout process
*/
class Login
{
/**
* #var object The database connection
*/
private $db_connection = null;
/**
* #var array Collection of error messages
*/
public $errors = array();
/**
* #var array Collection of success / neutral messages
*/
public $messages = array();
/**
* the function "__construct()" automatically starts whenever an object of this class is created,
* you know, when you do "$login = new Login();"
*/
public function __construct()
{
// create/read session, absolutely necessary
session_start();
// check the possible login actions:
// if user tried to log out (happen when user clicks logout button)
if (isset($_GET["logout"])) {
$this->doLogout();
}
// login via post data (if user just submitted a login form)
elseif (isset($_POST["login"])) {
$this->dologinWithPostData();
}
}
/**
* log in with post data
*/
private function dologinWithPostData()
{
// check login form contents
if (empty($_POST['user_name'])) {
$this->errors[] = "Username field was empty.";
} elseif (empty($_POST['user_password'])) {
$this->errors[] = "Password field was empty.";
} elseif (!empty($_POST['user_name']) && !empty($_POST['user_password'])) {
// create a database connection, using the constants from config/db.php (which we loaded in index.php)
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// change character set to utf8 and check it
if (!$this->db_connection->set_charset("utf8")) {
$this->errors[] = $this->db_connection->error;
}
// if no connection errors (= working database connection)
if (!$this->db_connection->connect_errno) {
// escape the POST stuff
$user_name = $this->db_connection->real_escape_string($_POST['user_name']);
// database query, getting all the info of the selected user (allows login via email address in the
// username field)
$sql = "SELECT user_name, user_email, user_password_hash
FROM users
WHERE user_name = '" . $user_name . "' OR user_email = '" . $user_name . "';";
$result_of_login_check = $this->db_connection->query($sql);
// if this user exists
if ($result_of_login_check->num_rows == 1) {
// get result row (as an object)
$result_row = $result_of_login_check->fetch_object();
// using PHP 5.5's password_verify() function to check if the provided password fits
// the hash of that user's password
if (password_verify($_POST['user_password'], $result_row->user_password_hash)) {
// write user data into PHP SESSION (a file on your server)
$_SESSION['user_name'] = $result_row->user_name;
$_SESSION['user_email'] = $result_row->user_email;
$_SESSION['user_login_status'] = 1;
} else {
$this->errors[] = "Wrong password. Try again.";
}
} else {
$this->errors[] = "This user does not exist.";
}
} else {
$this->errors[] = "Database connection problem.";
}
}
}
/**
* perform the logout
*/
public function doLogout()
{
// delete the session of the user
$_SESSION = array();
session_destroy();
// return a little feeedback message
$this->messages[] = "You have been logged out.";
}
/**
* simply return the current state of the user's login
* #return boolean user's login status
*/
public function isUserLoggedIn()
{
if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) {
return true;
}
// default return
return false;
}
}
Maybe the session can't be created. Did you use start_session() on your file?
echo username like that <?php echo (isset($_SESSION['name'])) ? $_SESSION['name'] : 'guest'; ?> and see if session has been created.
I'm assuming that there is some other code calling the login script. Anyways, that notice means that the 'name' key is not registered in the $_SESSION, which makes sense since I think you mean 'user_name'.
so try:
Hey, <?php echo $_SESSION['user_name']; ?>. You are logged in.
Try to close this browser tab and open it again. Still logged in! ;)
Logout
Otherwise you have to register the 'name' in the session, assuming $result_row has a name attribute:
if (password_verify($_POST['user_password'], $result_row->user_password_hash)) {
// write user data into PHP SESSION (a file on your server)
$_SESSION['name'] = $result_row->name;
$_SESSION['user_name'] = $result_row->user_name;
$_SESSION['user_email'] = $result_row->user_email;
$_SESSION['user_login_status'] = 1;
}
I see session_start in your Login::__construct function, but do you construct new Login before attempting to access $_SESSION variables? I'm not seeing that... I would suggest making sure session_start() is somewhere in your init code, called before anything else.
1st. Please move your session_start() to a file which will be included in all your php files and REMOVE it from your Login class :)
Perhaps you can move it to where you set constants as DB_HOST, DB_USER and etc..
2nd Check your $_SESSION keys :) you are setting $_SESSION['user_name'] but try to catch $_SESSION['name']
You can't access $_SESSION variable without starting a session. Also if you have already started the session anywhere before in your php file, then you will get warning that a session is already started. so consider using the following statement, before you access $_SESSION variable:
if( !session_id() ) session_start();
I'm trying to integrate a forum (created in Codeigniter) into a website (simple php >>> no framework used).
In order to automatically login to the forum, when I login in my website, I need to use a function of the forum which expects 2 parameters $username and $password.
I already have this informations (username and password) from my website, in $_SESSION.
How can I read the $_SESSION from the forum(as I say before Codeigniter based), because, I have no acces to it.
Is there a posibility to define 2 constants, somewhere in the core / config of the forum, to hold these details from $_SESSION, in order to have acces from anywhere inside the forum ?
I know that the sessions from CI are different from $_SESSION, so please help me with something more practical, in order to solve my problem.
Thanks.
Read this url;-
http://codeigniter.com/forums/viewthread/158923/#766011
http://codeigniter.com/forums/viewthread/188648/#892137
In case for those who want to do native session with 2.0.2
Just copy the native_session.php file to your application/libraries/ and rename it as Session.php
Then change the class name and constructor name to CI_Session
Also add the following then it should work fine.
function sess_destroy()
{
$this->destroy();
}
or
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Native / Database hybrid
Code Igniter
Citrusmedia - Matthew Lymer
*/
class CI_Session
{
var $sess_table_name = '';
var $sess_expiration = 7200;
var $sess_match_ip = FALSE;
var $sess_match_useragent = TRUE;
var $sess_time_to_update = 300;
var $encryption_key = '';
var $flashdata_key = 'flash';
var $time_reference = 'time';
var $gc_probability = 5;
var $userdata = array();
var $CI;
var $now;
/**
* Session Constructor
*
* The constructor runs the session routines automatically
* whenever the class is instantiated.
*/
function CI_Session($params = array())
{
log_message('debug', "Session Class Initialized");
// Set the super object to a local variable for use throughout the class
$this->CI =& get_instance();
// Set all the session preferences, which can either be set
// manually via the $params array above or via the config file
foreach (array('sess_table_name', 'sess_expiration', 'sess_match_ip', 'sess_match_useragent', 'sess_time_to_update', 'time_reference', 'encryption_key') as $key)
{
$this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key);
}
// Sessions, start your engines!
ini_set("session.gc_maxlifetime", $this->sess_expiration);
session_start();
// Load the string helper so we can use the strip_slashes() function
$this->CI->load->helper('string');
// Are we using a database? If so, load it
if( !$this->sess_table_name ) {
die('Session class database table name not configured');
}
$this->CI->load->database();
// Set the "now" time. Can either be GMT or server time, based on the
// config prefs. We use this to set the "last activity" time
$this->now = $this->_get_time();
// Set the session length. If the session expiration is
// set to zero we'll set the expiration two years from now.
if ($this->sess_expiration == 0)
{
$this->sess_expiration = (60*60*24*365*2);
}
// Run the Session routine. If a session doesn't exist we'll
// create a new one. If it does, we'll update it.
if ( ! $this->sess_read())
{
$this->sess_create();
}
else
{
$this->sess_update();
}
// Delete 'old' flashdata (from last request)
$this->_flashdata_sweep();
// Mark all new flashdata as old (data will be deleted before next request)
$this->_flashdata_mark();
// Delete expired sessions if necessary
$this->_sess_gc();
log_message('debug', "Session routines successfully run");
}
// --------------------------------------------------------------------
/**
* Fetch the current session data if it exists
*
* #access public
* #return bool
*/
function sess_read()
{
// Unserialize the session array
// $session = $this->_unserialize($session);
$session = array();
foreach( array('session_id', 'ip_address', 'user_agent', 'last_activity') as $key )
{
if( !isset($_SESSION[$key]) ) {
$this->sess_destroy();
return FALSE;
}
$session[$key] = $_SESSION[$key];
}
// Is the session current?
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
{
$this->sess_destroy();
return FALSE;
}
// Does the IP Match?
if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address())
{
$this->sess_destroy();
return FALSE;
}
// Does the User Agent Match?
if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 50)))
{
$this->sess_destroy();
return FALSE;
}
$this->CI->db->where('session_id', $session['session_id']);
if ($this->sess_match_ip == TRUE)
{
$this->CI->db->where('ip_address', $session['ip_address']);
}
if ($this->sess_match_useragent == TRUE)
{
$this->CI->db->where('user_agent', $session['user_agent']);
}
$query = $this->CI->db->get($this->sess_table_name);
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);
In the current login method:
$sth = $this->db->prepare("SELECT id, username, active FROM user WHERE username = ? AND password = ?");
$sth->setFetchMode(PDO::FETCH_OBJ);
$sth->execute(array($username, $password));
if (($obj = $sth->fetch()) !== FALSE)
return $obj;
And on the login.php file.
$auth = new Auth($db);
$user = $auth->login('username', 'password');
if ($user) {
if ($user->active == 0) { die('You must activate your account')}
//If all is okay... Set the session variables...
}
But I was told that I rather would set the session variables in the login() method, but If I do so, how should I instead handle the checks like if the user is activated or not?
I'd probably create a structure like this:
class Auth {
public function login($user, $pass);
public function logout();
public function loggedIn();
private function getUserSession();
private function updateUserSession();
private function deleteUserSession();
}
login() checks against the database and on authentication success (if the user is active, user:password match and other tests) runs updateUserSession(). Ends by returning the result of $this->loggedIn().
logout() unsets the session with deleteUserSession().
loggedIn() checks against the session with getUserSession() and returns true or false if the user is logged in.
You could do it in either procedure. The session vars are the same.
To check for an active user just add a " and userActive = 1" in your query. To deactivate a user just change this column to a 0 for that user.