Class static variables reset when I call them in other file - php

I am practicing PHP, and the issue I encountered today is my static variable getting reset every time I call it.
Login Page after verfied user from DB
<?php
Session::onlogin(1);
?>
This is my session class it has a func onlogin and I send some data to it from another file which change $is_signed to true. But the issue is variable $is_signed getting reset when I call it from index.php it returns false
<?php
class Session {
private static $is_signed = false;
function __construct(){
session_start();
}
public static function is_signed_in(){
return self::$is_signed;
}
public static function onLogin($userid){
if($userid){
session_regenerate_id();
$_SESSION['user_id'] = $userid;
self::$is_signed = true;
return true;
}
}
}
$session = new Session;
?>
Now I am calling it in index.php as below
if(Session::is_signed_in()){
echo "logged In";
}
else {
echo "error";
?>
I don't know where I am creating any error but when I call the methods.

So i asume this
class.php
class Session
{
private static $is_signed = false;
function __construct()
{
session_start();
}
public static function is_signed_in()
{
return self::$is_signed;
}
public static function onLogin($userid)
{
if ($userid) {
session_regenerate_id();
$_SESSION['user_id'] = $userid;
self::$is_signed = true;
return true;
}
}
}
$session = new Session;
login.php
<?php
require 'class.php';
$session = new Session;
Session::onlogin(1);
var_dump(Session::is_signed_in());// output true
index.php
<?php declare(strict_types = 1);
require 'class.php';
var_dump(Session::is_signed_in());// output false
think about it that login.php and index.php are 2 separate programs not aware one of each other.Thats why you try put SESSION there change
function __construct()
{
session_start();
if (isset($_SESSION['user_id'])){
self::$is_signed = true;
}
}
and you are done

Related

Session not getting the variable prints long string

I have this session class
class Session
{
public function __construct()
{
if (!isset($_SESSION)) {
$this->initSession();
}
}
public function setSessionId()
{
$_SESSION['Id'] = session_id();
}
public function getSessionId()
{
return $_SESSION['Id'];
}
public function initSession()
{
session_start();
error_reporting(E_ALL);
$this->setSessionId();
}
public function isLogged(){
if(isset($_SESSION['Id'])){
return true;
}else{
$this->deleteSession();
return false;
}
}
In my login.php I pass the id to my session but
$results['Id'] = session_id();
when I got to index.php and echo the Id it echos a long string not the current user Id
$session = new Session();
$id = $session->getSessionId();
echo $id;
Please help me how do I pass the variable!I have tried a lot but I seem to be stuck here!Would really appreciate some help
Add additional methods to your class:
public function setUserId($userid) {
$_SESSION['user_id'] = $userid;
}
public function getUserId() {
return isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
}
Then your login page should call $session->setUserId() after the user logs in, passing the ID from the database.

Set and get sessions

I am trying to set a php session from my loginpage:
if($results){
$session->setId($results['Id']);
}
In my session class I have these:
class Session{
public function createSession(){
session_start();
error_reporting(E_ALL);
}
public function getId(){
return $_SESSION['Id'];
}
public function setId($value){
$_SESSION['Id'] = $value;
}
}
Then I try to call it to the index my Id
$thisSession=Session::getId();
if(isset($thisSession)) {
echo "The session is set.";
} else{
echo "Sorry, it's not set.";
}
How can I do it?
Undefined index: Id
To pass the session id from login to my index page!
You can for sure create an object that encapsulate the $_SESSION but be careful about how PHP works.
I suggest small modifications to your class (if it's ok to you) using the session_id method :
class Session
{
public function __construct()
{
if (!isset($_SESSION)) {
$this->initSession();
}
}
protected function initSession()
{
session_start();
error_reporting(E_ALL);
$this->setSessionId();
}
public function setSessionId()
{
$_SESSION['Id'] = session_id();
}
public function getSessionId()
{
return $_SESSION['Id'];
}
}
Keep in mind that $_SESSION variables are accessible by users easily don't put in it too much informations, especially sensitive.
$_SESSION is a PHP superglobal variable you can retrieve it wherever your want to, but you can get it by declare :
$session = new Session();
$id = $session->getSessionId();
var_dump($id);
For logout you should add this method :
public function deleteSession()
{
session_destroy();
}
And then use when disconnected action is asked
$session = new Session();
$session->deleteSession();

variable won't change in PHP class

The method -- initially called in index.php -- redirects to another page. The problem here is that variable $logged_in isn't getting assigned a new value... which means that when the variable is used in the other page, it is read as false.
NOTE: The assignment of session 'id' and session 'type' is correct.
class Session {
public $logged_in = false;
public function login($data) {
if ($data) {
$_SESSION['id'] = $data['id'];
$_SESSION['type'] = $data['type'];
$this->logged_in = true;
}
}
}
This is a class and therefore is lost (its properties are lost) at the end of the first scripts execution and then recreated in the second in its initial state.
Classes do not live across executions of the same script or any other script.
If you wish to maintain the objects state, you will have to save the state to a file or maybe the real SESSION so you can re-hydrate the data when the second script starts
session_start();
class Session {
public function login($data) {
if ($data) {
$_SESSION['id'] = $data['id'];
$_SESSION['type'] = $data['type'];
$_SESSION['logged_in'] = true;
}
}
// getter function
public function is_logged_in()
{
// just in case check
if ( isset($_SESSION['logged_in']) ) {
return $_SESSION['logged_in'] == true;
} else {
return false;
}
}
}
Called like this
$s = new Session();
if ( ! $s->is_logged_in() ) {
header('Location: index.php');
exit;
}
To keep it away from the SESSION completely you could
class Session {
public $id;
public $type;
public $logged_in;
public function __construct()
{
if ( file_exists('my_session.txt')) {
$obj = json_decode(file_get_contents('my_session.txt'));
foreach($obj as $prop => $val) {
$this->{$prop} = $val;
}
}
}
public function __destruct()
{
file_put_contents('my_session.txt', json_encode($this));
}
public function login($data) {
if ($data) {
$this->id = $data['id'];
$this->type = $data['type'];
$this->logged_in = true;
}
}
}
$obj = new Session();
$obj->login(array('id'=>99, 'type'=>'TEST'));
print_r($obj);
$obj = null;
echo 'object nulled' . PHP_EOL;
print_r($obj);
echo ' NOTHING should be printed' . PHP_EOL;
echo 'object rehydrated' . PHP_EOL;
$obj = new Session();
print_r($obj);
create another method check_login() to re-assign the values in the new page and call it within __construct()
function __construct(){
$this->check_login();
}
public function check_login(){
if(isset($_SESSION['id']) && isset($_SESSION['type']){
$this->logged_in = true;
} else {
$this->logged_in = false;
}
}

unset a session then return its data

I want to get a session and then return its data then unset it (or get a session and then unset it then return the data), I am doing 2 (header) redirects. after setting the session till getting the session.
but the problem is its not returning anything.
following is the class I am using:
class Session {
private $session_data1;
public function __construct() {
session_start(); // starts session on all files at first...
}
public function set_session($session_name, $session_data) {
return ($_SESSION[$session_name] = $session_data) ? true : false;
}
public function get_session($session_name) {
return isset($_SESSION[$session_name]) ? $_SESSION[$session_name] : false;
}
public function get_session_once($session_name) {
$this->session_data1 = $this->get_session($session_name);
$this->unset_session($session_name);
return $this->session_data1;
}
public function unset_session($session_name) {
if (isset($_SESSION[$session_name])) {
unset($_SESSION[$session_name]);
// return true;
}
}
public function destroy_all_session() {
session_destroy();
}
}
$session = new Session();
I am using 'set_session()' to set a session and wanted to use 'get_session_once()' which will unset the session and then return the value of that session.
if I dont unset it in the method 'get_session_once()' then it works, like the following:
public function get_session_once($session_name) {
$this->session_data1 = $this->get_session($session_name);
// $this->unset_session($session_name);
return $this->session_data1;
}
I am new in PHP, please help
I tested this, and for me it's working.
<?
$session = new Session();
$session->set_session('Username', 'StackOverflow');
echo $session->get_session_once('Username'); // echos 'StackOverflow'
echo $session->get_session_once('Username'); // no echo
?>
This is still the same:
public function get_session_once($session_name) {
$this->session_data1 = $this->get_session($session_name);
$this->unset_session($session_name);
return $this->session_data1;
}
Maybe the header redirect is the cause, it might be clear/delete the session.
Did you put session_start() at the start of every page?

how to use global variables in php class in a MVC project

I want to $st_id in a function in my model class in a mvc project, as you see below, but it get me an error that $st_id is not defined. what I can do for resolve this problem ?
<?php
#session_start();
$st_id=$_SESSION['username'];
if (!isset($_SESSION['USERNAME']))
{
header('Location: signin.php');
}
//////////////////////
class model
{
private $result;
public $rp_result;
//////////
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}
?>
How do you call your model ?
I suggest you:
class model
{
private $result;
public $rp_result, $st_id;
public function __construct($st_id)
{
$this->st_id = $st_id;
}
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}
And now, you can use:
#session_start();
$st_id=$_SESSION['username'];
if (!isset($_SESSION['USERNAME']))
{
header('Location: signin.php');
}
$model = new model($st_id);
$model->exe_query();
You have to declare it within the class if you're using it with $this
class model {
public $st_id;
public function __construct() {
#session_start();
$this->st_id = $_SESSION['username'];
}
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}
Why not call it directly as $_SESSION['username']? It's already global...

Categories