issue with static class property in php - php

I am working on a simple anonymous login system and I have a Session class which looks like this:
<?php
class Session
{
private static $cookieLifeSpanInDays;
public function __construct()
{
self::$cookieLifeSpanInDays = 1825;
}
public static function loginUser()
{
if (!Session::isLoggedIn())
{
// Login User
$session_id = Session::newSessionId();
$name = Session::newUserName($session_id);
if (empty($name))
throw new Exception('Failed to generate a unique user name. Try again later.');
DB::insert('users', array(
'name' => $name,
'session_id' => $session_id,
'last_login' => time()
));
setcookie("sessionId", $session_id, time() + (self::$cookieLifeSpanInDays * 86400), '/', $_SERVER['HTTP_HOST']);
$_SESSION['isLoggedIn'] = true;
var_dump(self::$cookieLifeSpanInDays);
var_dump($_COOKIE);
exit();
}
// Defaults
return true;
}
}
When I call the class like this: Session::loginUser();
The var_dumps() in the loginUser function looks like this:
So, my login function is broken (no cookie is getting set) because the static property on class self::$cookieLifeSpanInDays is null. What am I doing wrong here?

I've fixed it:
<?php
class Session
{
private static $cookieLifeSpanInDays = 1825;
public static function loginUser()
{
if (!Session::isLoggedIn())
{
// Login User
$session_id = Session::newSessionId();
$name = Session::newUserName($session_id);
if (empty($name))
throw new Exception('Failed to generate a unique user name. Try again later.');
DB::insert('users', array(
'name' => $name,
'session_id' => $session_id,
'last_login' => time()
));
setcookie("sessionId", $session_id, time() + (self::$cookieLifeSpanInDays * 86400));
$_SESSION['isLoggedIn'] = true;
var_dump(self::$cookieLifeSpanInDays);
var_dump($_COOKIE);
exit();
}
// Defaults
return true;
}
}

Related

How to pass calculated/final value of one function to other functions in a controller of Codeigniter application

Using sessions we can achieve this, but need this without sessions or cookies.
<?php
class Employees extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew()
{
$response = array();
$this->auth(); // this value is always null returned by auth() method
}
}
?>
This is more of a OOP programming basics question. If you want to re-use a variable in another function of the same controller object, you have to set the variable globally for the Employees class and then set/get its value in your functions by using $this->yourVariableName. But the set value of the object instance can only be reused in that instance only. Which means that after the auth() function, another function should be called subsequently to "access" the $this->yourVariableName.
Another way is to pass the $jwtoken as a parameter to a function.
But the following code answers your question "How to pass calculated/final value of one function to other functions in a controller of Codeigniter application", if it doesn't, then your question should be corrected I guess.
Edit:
Ow ok, first the auth() function is being called, then you would like to pass the $jwtoken value to another function, am I right? Well once a function is finished executing, the variable "disappears" if not passed to another function. If you would like to process the $jwtoken value immediately within the auth() function, then the answer is to pass the $jwtoken value to another function from within the auth() function:
<?php
class Employees extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
// this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
$this->addNew($jwtoken);
// What is the addNew() supposed to do?
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew($jwtoken = "default_value_if_not_set") {
echo $jwtoken;
}
}
Since you are creating an API, I assume the API is a REST api and stateless, so there is no interference of sessions and cookies.
I assume your process works like this:
User does a login request from the app to the api and the api returns a token when the credentials check is valid
The token is stored in the app (in a local database for example) and used for other requests
So the only thing you need to do is (I assume you have a route to addNew):
public function addNew() {
$token = $this->input->get('token');
$loginData = $this->validateToken($token);
//... add new process
}
And from your app you need to pass the token with the request to the api.
How do you validate the token?
To obtain the data you have set in the token, you have to decode the token:
/**
* throws SignatureInvalidException
*/
function validateToken($token)
{
$jwt = new JWT();
return $jwt->decode($token, jwtSecretKey, 'HS256');
}
Code improvement
Avoid using sessions and cookies
Since your api is stateless, you have to avoid settings cookies or sessions. So in your controller you can remove the flash data helper:
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
# REMOVE THIS LINE
# $this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => "Wrong email or password", //CHANGE THIS LINE
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
# REMOVE THIS LINE
# $this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => "Scucessfully login!", //CHANGE THIS LINE
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
Return the output response instead of $jwtoken
In your response you have already set the the token, so you can simply return the response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($response));
Your query is vulnerable to sql injections
Use escape method around you variables or bind the params:
$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));

Save session/cookies like discord in php

I would like to save sessions and cookies as discord does. What i mean? I mean when user sign in to discord account on browser and delete all cookies/session on browser by clicking padlock and cookies. When that will deleted everytime session file is created. And when i refresh site i was still logged on account. I want do something on this same way but when i use session, cookies, Header (to header i cant add expires date) And delete cookies by this same way it not adding that again because my script cant get any information about user. I thinking to do a JavaScript while to add every second sessionstorage or localstorage. And check that everytime when user open site but that is not good for optimalization. So anyone had idea how to do that?
Update
CreateInfo.php
<?php
namespace Client\Info;
use Client\Info\CheckInfo;
use Client\Info\SetInfo;
class CreateInfo
{
public function __construct()
{
$this->checkInfo = new CheckInfo();
$this->setInfo = new SetInfo();
$this->status = $this->checkInfo->getStatus();
}
public function control()
{
if($this->status['session'] && $this->status['cookie'] && $this->status['sameCookieSession']){
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, true, true);
}
}else if($this->status['session'] && $this->status['cookie'] && !$this->status['sameCookieSession']){
$this->setInfo->addCookie(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, true, false);
}
}else if($this->status['session'] && !$this->status['cookie']){
$this->setInfo->addCookie(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, false, false);
}
}else if(!$this->status['session'] && $this->status['cookie']){
$this->setInfo->addSession(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(false, true, false);
}
}else{
$this->setInfo->setAll();
}
}
public function run()
{
$this->control();
}
}
CheckInfo.php
<?php
namespace Client\Info;
use Client\Info\InfoDatabase;
use Client\Cookie\CookieFunction;
use Client\Session\SessionFunction;
use Client\Ip\IpFunction;
class CheckInfo
{
public function __construct()
{
$this->infoDatabase = new InfoDatabase();
$this->cookieFunction = new CookieFunction();
$this->sessionFunction = new SessionFunction();
$this->ipFunction = new IpFunction();
$this->session = $this->sessionFunction->getSession('client');
$this->cookie = $this->cookieFunction->getCookie('client');
}
public function checkExist($data)
{
if(!isset($data) || empty($data)){
return false;
}
if(!$this->infoDatabase->checkExistInDb($data)){
return false;
}
return true;
}
public function getStatus()
{
if($this->checkExist($this->cookie)){
if($this->checkExist($this->session)){
if($this->cookie == $this->session){
return[
'session' => true,
'cookie' => true,
'sameCookieSession' => true
];
}else{
return[
'session' => true,
'cookie' => true,
'sameCookieSession' => false
];
}
}else{
return[
'session' => false,
'cookie' => true,
'sameCookieSession' => false
];
}
}else{
if($this->checkExist($this->session)){
return[
'session' => true,
'cookie' => false,
'sameCookieSession' => false
];
}else{
return[
'session' => false,
'cookie' => false,
'sameCookieSession' => false
];
}
}
}
public function checkIpStatus()
{
$ip = $this->ipFunction->getIp();
$result = false;
if($this->getStatus()['session']){
$result = $this->infoDatabase->checkExistIpInDb($this->session, $ip);
}else if($this->getStatus()['cookie']){
$result = $this->infoDatabase->checkExistIpInDb($this->cookie, $ip);
}
return $result;
}
}
SetInfo.php
<?php
namespace Client\Info;
use Client\Info\InfoDatabase;
use Client\Cookie\CookieFunction;
use Client\Session\SessionFunction;
use Client\Ip\IpFunction;
use Client\Currency\CurrencyFunction;
use App\Element\Random\RandomString;
class SetInfo
{
public function __construct()
{
$this->infoDatabase = new InfoDatabase();
$this->cookieFunction = new CookieFunction();
$this->sessionFunction = new SessionFunction();
$this->ipFunction = new IpFunction();
$this->currencyFunction = new CurrencyFunction();
$this->randomString = new RandomString();
$this->cookie = $this->cookieFunction->getCookie('client');
$this->session = $this->sessionFunction->getSession('client');
}
public function addIp($session, $cookie, $sameCookieSession)
{
$ip = $this->ipFunction->getIp();
if($sameCookieSession){
$this->infoDatabase->addIp($this->cookie, $ip);
}else{
if($session){
$this->infoDatabase->addIp($this->session, $ip);
}else if($cookie){
$this->infoDatabase->addIp($this->cookie, $ip);
}
}
}
public function addCookie($session)
{
if($session){
$this->cookieFunction->setCookie('client', $this->session);
}
}
public function addSession($cookie)
{
if($cookie){
$this->sessionFunction->setSession('client', $this->cookie);
}
}
public function setAll()
{
$rand = $this->randomString->generate(128);
$ip = $this->ipFunction->getIp();
$currency = $this->currencyFunction->getCurrencyCode();
$this->infoDatabase->addCookie($rand);
$this->infoDatabase->addIp($rand, $ip);
$this->infoDatabase->addCurrency($rand, $currency);
$this->cookieFunction->setCookie('client', $rand);
$this->sessionFunction->setSession('client', $rand);
}
}

Laravel 4.2 session::get() method not returning session data in controllers

Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}

php global variable is null

I have a protected $headers variable in my class assigning a value using the function
public function actionLogIn()
{
$userCode = Input::get('username');
$password = Input::get('password');
$loginData = array(
'code' => $userCode,
'passkey' => $password
);
$loginData = json_encode($loginData);
$this->headers = Auth::login($loginData);//Modified login method
if(! is_null($this->headers))
{
return View::make('forms.welcome')->with('title', 'Welcome');
}else{
echo "Invalid access!";
}
}
and when I use print_r($this->headers); it successfully prints out the value I need,
but when I tried to access $this->headers using the function:
public function actionLogOut()
{
if(is_null($this->headers)){
echo "is null", "\n";
}//for checking only
Auth::logout($this->headers);
}
$this->headers is null. What could be the problem ? also $headers is actually an array. Thanks!
A new controller instance is created for every request. That means that even though you store information in $this, it's not there when the user requests a new page.
What you want to do is store data in something that doesn't change between requests - either in the session or in cookies.
In the session, it would look like this: (warning - untested code)
public function actionLogIn() {
...
$loginData = json_encode($loginData);
$user = Auth::login($loginData);
if ($user) {
Session::put('logged_in_user',$user);
return View::make('forms.welcome')->with('title', 'Welcome');
}else{
echo "Invalid access!";
}
}
public function actionLogOut() {
if(Session::has('logged_in_user'){
$user = Session::get('logged_in_user');
Auth::logout($user);
Session::forget('logged_in_user');
} else {
echo "is null\n";
}
}
Take a look at http://four.laravel.com/docs/session for more information on Sessions in Laravel.

Codeigniter find whether user logged in or not

In codeigniter I am trying to include a Logger library and in the below code I need to check whether a user has logged in or not and if so, find his user id.
<?php
class Logger {
private $CI;
public function __construct() {
$this->CI =& get_instance();
}
public function request_logger() {
$uri = $this->CI->uri->uri_string();
$ip="";
$userID="";
//$ip = ip2long($_SERVER['REMOTE_ADDR']);
$ip = $_SERVER['REMOTE_ADDR'];
$params = trim(print_r($this->CI->input->post(), TRUE));
log_message('info', '==============');
log_message('info', 'URI: ' . $uri);
log_message('info', '--------------');
log_message('info', 'PARAMS:' . $params);
log_message('info', 'IP:' . $ip);
log_message('info', '==============');
//if ($this->ion_auth->logged_in())
if(isset($_POST['user_id']))
{
log_message('info', '<== Inside loggedin loop ==>');
$userID=$this->input->post('user_id');
}
log_message('info', 'USERID' . $userID);
}
}
?>
you can use codeigniter Session class.
you can create new session with user data,like this
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
and you can access this data via,
$userId = $this->session->userdata('userid');
Visit this User GuideCodeignitor Session

Categories