Can not call Static variable - php

I am brand new to PHP and have a simple project, I do Java.
In my simple project I have some html files and some Php files.
I connect to a device via SSH in my Php web page, and after that I am gonna run some commands and return back SSH returned data.
Any ways, So I designed a Html file for Login and use that in my php, here is my Php code :
<?php
class Connection {
public static $ip; // I even made static this variable to test if I can access Static variable from other
public $username;
public $password;
public static $ssh;
public function sshConnection() {
include ('./view/login.html'); // The html page contain variables
include('Net/SSH2.php'); // I use phpseclib to connect via SSH
if(isset($_POST['lgin'], $_POST['ip'], $_POST['username'], $_POST['password'])) { // Login button in html file
$this->ip = $_POST['ip']; // input type to get ip in html file
$this->username = $_POST['username']; // input type to get username in html file
$this->password = $_POST['password']; // input type to get password in html file
$this->ssh = new Net_SSH2($this->ip);
if (!$this->ssh->login($this->username, $this->password)) {
print('Login faild');
} else {
header("Location: http://localhost/wireless/configwireless.php"); // This redirect to next page that I should display some Commands
}
}
}
}
$connection=new Connection();
$connection->sshConnection();
?>
I need $ssh variable in next page so that I can run commands via this connection and make sessions.
I googled and find out I can access the static variable via this code :
classname::$variableName;
I even made my $ip variable static to test if I can access that or not, But no chance,
Here is my configwireless.php Code :
<?php
echo Connection::$ip; // Does not display the input ip variable.
?>
But it does not display the $ip variable.
Where I am doing wrong?

For assignment static property in class, should be used self or static keyword. So instead of
$this->ip = $_POST['ip'];
use this
static::$ip = $_POST['ip'];
or
self::$ip = $_POST['ip'];

As my dear friend #Mohammad notice, after header("Location: http://localhost/wireless/configwireless.php"); variables will be lost.
I did this before header("Location: http://localhost/wireless/configwireless.php");:
session_start();
$_SESSION['ip'] = $this->ip;
And in next page I added :
session_start();
$x=$_SESSION['ip'];
echo $x;

Related

include variables twice from a php file

I have a simple user files like this
joe.php
<?php
$pass = 'joepassword';
$userpath = 'work/joe';
?>
sam.php
<?php
$pass = 'sampassword';
$userpath = 'work/sam';
?>
I use these files for text authentication one is included once the user logs in setting the path for that user while checking the authentication. Once authenticated, I immediately overwite that $pass variable with"text" so the password is not available as a variable to prying eyes.
Now I need to log in as "joe"
so I include joe.php sessing $userpath
$userpath='work/joe'
I now need for admin purposes, to access sam's $userpath as a destination, and joe's $userpath as a source at the same time but if I include sam.php I will be overwithing joe's $userpath
I figure there is a simpler solution like using fopen and extracting only the (second) path for sam, but not sure how to go about this.
I am not posting this for a lecture in security so please abstain from responding about secirity. These files are not in a folder accessible to the web server anyway.
Make them classes:
class Sam() {
public $userPath;
public $password;
public __construct($path,$password) {
$this->userpath = $path;
$this->password = $password;
}
}
class Joe() {
public $userPath;
public $password;
public __construct($path,$password) {
$this->userpath = $path;
$this->password = $password;
}
}
$joe = new Joe("user path here", "my password");
$sam = new Sam("another user path", "another password");
echo $joe->userPath;
echo $sam->userPath;
echo $joe->password;
echo $sam->password;
Despite most people barfing up the wrong tree which do not answer the question, the answer is amazingly simple. Set session variables from the originally included file and use the session variables from then on. The second call to that or similar file set a second set of session variables.
after including joe.php in auth.php
$_SESSION['userpath']=$userpath;
Then , even on the same page or other pages we can include
joe.php
<?php
$pass = 'joepassword';
$userpath = 'work/joe';
?>
now when we include sam.php (the second one)
$_SESSION['touserpath']=$userpath;

PHP login issue when moving to a different server

I have a very basic log in system, which I have tested on my localhost as well as a free hosting site I use to test my projects and all worked fine.
I have just moved the site to Site Ground as a subdomain and the login has stopped working. The site is still loading content from the database I have created in this location, so I know the issue is not a result from a failure to connect to the database.
There is nothing in the .htaccess file to block a user login either, if it is an issue with moving it to a new server, how would I find a way around this? The page does NOT return any error when attempting to login
login PHP:
<?php
require 'includes/connect.php';
session_start();
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5 ($_POST['password']);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT COUNT(user_id) FROM nathan WHERE username='$username' AND password='$password'";
$q = $pdo->prepare($sql);
$q->execute();
$count = $q->fetchColumn();
if($count == 1){
$_SESSION['username'] = $username;
header('Location: admin.php');
}
}
?>
DB connection:
<?php
class Database
{
private static $dbName = "some_DB" ;
private static $dbHost = "localhost" ;
private static $username = "some_user";
private static $password = "password123";
private static $cont = null;
public function __construct() {
die('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$username, self::$password);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
Session PHP:
<?php
session_start();
if (!isset($_SESSION['username'])){
header('Location: login.php');
};
?>
You might want to inspect your cookies when viewing and verify that you indeed are getting a cookie set with session information. If this isn't working, my limited view of your environment would suggest that you're not allowing cookies from that specific subdomain.
Another thing to check is the directory where sessions data is stored. If that isn't populated, then you're not going to be able to persist a session.
As the poster above me said it is definitely because of the cookies, refer to this post for solutions PHP Sessions across sub domains
And you shouldn't store password directly in the database, it is insecure, you should hash it with password_hash(), and then compare it with hash_equals(), on login.

Variables from Session Class not passing to new pages

I defined a session class,which uses values from the $_POST variable in an array called $sessionVars. When a user logs-in a new instance of the session class is created, a construct function sets session variables.I checked that this is working correctly.Problem: When i try to access those variables from a different page the session shows that its not started and those variables are undefined. Confused cause I thought $_SESSION being a super global means its accessible all the time(i.e scope doesn't matter) . I suspect im doing something wrong when I try to access the $_SESSION variables since they are in a class. I appreciate any help..thanks in advance.
class userSession{
public function __construct($sessionVars){
session_start();
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
/*just for housekeeping. not used in application*/
function showvars(){
echo $_SESSION['userEmail'].'<br><br>';
echo $_SESSION['userID'].'<br><br>';
echo $_SESSION['userFolder'];
$sessionID=session_id();
echo '<br><br>'.$sessionID;
}
}//**END USER SESSION
/*This is the login script that calls the session*/
include 'library.php';
$show=new render;
$show->index();
if(!isset($_POST['login']) ){
$show->usrLogin();
} else{
if(!empty($_POST['email'])){
$postVars=array('user'=>$_POST['email'],'pass'=>$_POST['password']);
$user=new user();
$data=$user->loginUser($postVars);
$currSession=new userSession($data);
}else{
die('No data in POST variable');}
}
/*file upload that needs the session[userFolder] variable*/
function file_upload(){
$userFolder=&$_SESSION['userFolder'];
echo '<hr>userFolder is : '.$userFolder;
function do_upload(){
if(!empty( $_FILES) ){
echo $userFolder.'<hr>';
$tmpFldr=$_FILES['upFile']['tmp_name'];
$fileDest=$userFolder.'/'.$_FILES['upFile']['name'];
if(move_uploaded_file($tmpFldr,$fileDest)){
echo 'file(s) uploaded successfully';
}
else{
echo 'Your file failed to upload<br><br>';
}
return $fileDest; //returns path to uploaded file
} else{die( 'Nothing to upload');}
}//END FUNCTION DO_UPLOAD,
/*Perform upload return file location*/
$fileLoc=do_upload();
return $fileLoc;
}
You need to instantiate an object of this class on every page that uses the session (or start the session manually). Also, you'll not want that constructor, instead some other way of setting vars. This is just for illustration of how it works with your current code, there are much better approaches:
class userSession {
public function __construct(){
session_start();
}
function set_login_vars($sessionVars){
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
}
//page1.php
$session = new userSession;
$session->set_login_vars($loginVars);
//page2.php
//you need to start the session, either with the class
$session = new userSession;
//or session_start();
print_r($_SESSION);

Compare values given by user to values in ini file

I am trying to make a login validation page for my class and this is the code I have for the page LoginDataModel.php.
<?php
//define a constant variable for fxUsers.ini
define('FX_LOGIN_INI_FILE', 'fxUsers.ini');
class LoginDataModel {
private $ini_array;
//construct class will read and store an associative array
public function __construct() {
$this->ini_array = parse_ini_file(FX_LOGIN_INI_FILE);
}
//validateUser function will compare the username and password
//given by the user to the values stured in the ini file.
public function validateUser($username, $password){
if(in_array($username,$this->ini_array) && in_array($password,$this->ini_array)){
return TRUE;
} else {
return FALSE;
}
}
}
?>
This code will be called in my login.php page once the user passes through his credentials. If the users credentials do not match, he will simply be rerouted back to the login page to try again. The code for the login page is
<?PHP
//check for key to see if this is the first time loading the page
if (empty($_POST['txtUser'])){
$user = '';
$pass = '';
} else {
$user = $_POST['txtUser'];
$pass = $_POST['txtPassword'];
}
//call method from a different file
require_once ('LoginDataModel.php');
$LoginDataModel = new LoginDataModel();
$control = $LoginDataModel->validateUser($user, $pass);
//if user and password match, continue to next file and exit current file
if($control === TRUE){
include 'fxCalc.php';
exit();
}
?>
While I believe to have everything set, The only thing I need is how to compare the values between the user and the values in the ini file. Any help would be appreciated
EDIT
I should have mentione that my ini file will just be
[section]
admin = pass
EDIT 2
My code reflect the changes I've made thanks to the support from this post as well as looking back at my text book. My problem is now that When I pass the user and pass through the file, it returns as false even though the strings match perfectly.
You are doing the wrong way of comparison in the below line..
if($ini_array == $username && $ini_Array == $password){
The parse_ini_file() returns an array , so you just can't check a variable $username inside an array (i.e. $ini_array) using a == operator. You should be using array_search or in_array() functions as such.
Something like...
if(in_array($username,$ini_array) && in_array($password,$ini_Array)){

PHP - Accessing my user class from the whole app

I am currently writing a login script because I am trying to learn PDO using OOP. I have a index.php page which only contain a login form. Then I have a User class, it looks like this:
<?php
include_once('database.php');
session_start();
class User{
public $id;
public $username;
public $password;
public $firstname;
public $lastname;
public function Login($username, $password) {
$db = new Database;
$db = $db->dbConnect();
$query = "SELECT * FROM users WHERE username = ? AND password = ?";
$statement = $db->prepare($query);
$statement->bindParam(1, $username);
$statement->bindParam(2, $password);
$statement->execute();
$rows = $statement->rowCount();
$data = $statement->fetchAll();
if( $rows == 1 ) {
$this->id = $data[0]['id'];
$this->username = $data[0]['username'];
$this->password = $data[0]['password'];
$this->firstname = $data[0]['firstname'];
$this->lastname = $data[0]['lastname'];
$_SESSION['SESSID'] = uniqid('', true);
header("location: dashboard.php");
}
}
}
?>
When the user is signed-in he/she goes to dashboard.php. I want to access the current User class from there, so I can use echo $user->username from there. But in dashboard.php, I have to declare the User class as new, so it doesn't keep all the variables.
Do you have any ideas on how i can access the User class variables in Dashboard.php which was declared in the Login-function?
Sorry for the bad explanation, but I hope you understand. Thank you in advance!
First off put your user class definition in another file and load it in like you do your database.php. In there you want only your class definition none of the session start business... <?php class User {....} ?> (the closing ?> is optionial).
so what you have now on your pages that need access to the user object is
<?php
include_once('database.php');
include_once('user.php');
session_start();
Then after a user has successfully logged you tuck the user in the session.
$_SESSION["user"] = $user;
Then when you want to get at it just say
$user = $_SESSION["user"];
echo $user->username;
What you could do is, put your user object into the session:
$obj = new Object();
$_SESSION['obj'] = serialize($obj);
$obj = unserialize($_SESSION['obj']);
or you could create a singleton, check out this link:
Creating the Singleton design pattern in PHP5
You have 2 options:
a) You store all the login info in a session.
b) You only store the user ID and some sort of identifier that the user has / is logged in, and create another method that will load the information from the database each time you load the page (bad idea really)
For example, you could add the following methods to your class in order to implement the above mentioned functionality and some more:
function createUserSession(array $userData) {
// Create / save session data
}
function readActiveUserSession() {
// Read current user information
}
function destroyActiveUserSession() {
// Call to destroy user session and sign out
}
Of course, you will have to add the appropriate code to the methods.

Categories