Refer to a global variable doesn't work - php

A im writing a simple script in PHP with few files, in 'loginForm.php' I have code:
<?php
session_start();
$login = $_GET['login'];
$password = $_GET['password'];
$remember = $_GET['remember'];
include_once("login.php");
$userAccount = new UserAccount($login, $password);
$logged = $userAccount -> isLogged();
(...)
and in file 'photo.php':
global $userAccount;
$login = $userAccount -> getLogin();
what gives mi an error:
Call to a member function getLogin() on a non-object
I also tried with $GLOBALS - same result.

Global variable does not work across requests, but have file scope.
the typical use of global variables if to have a variable that is accessible across different scopes (normally functions in the same file.
For example in file1.php
<?php
$value = 1;
echo $value; // prints '1'
function f1() {
global $value;
$value++;
}
echo $value; // prints '2'
function f1() {
$value++;
}
echo $value; // prints '2'
?>
To use variables across requests, use sessions.
safest way to create sessions in php
Storing objects in PHP session

OK, now i did:
1) In AJAX-request file i create a instance of Class UserAccount, which will be store in $_SESSION array
<?php
include_once("login.php");
session_start();
$login = $_GET['login'];
$password = $_GET['password'];
$rememberMe = $_GET['remember'];
$userAccount = new UserAccount();
$userAccount -> LogIn($login, $password);
$logged = $userAccount -> isLogged();
$_SESSION['userAccountClassObject'] = serialize($userAccount);
2) In static (non AJAX-request) file 'photo.php' it works fine:
<?php
include_once("login.php");
$user = unserialize($_SESSION['userAccountClassObject']);
$login = $user -> getLogin();
3) But in other AJAX-request file - addComment.php unfortunatelly doesn't work:
<?php
$id = $_GET['id'];
$comment = $_GET['comment'];
session_start();
include("login.php");
$user = unserialize($_SESSION['userAccountClassObject']);
$login = $user -> getLogin(); // Fatal error

Related

php sessions not storing data

I'm currently having trouble with storing session data.
For some reason my sessions start and I can see it as a cookie but when I try to get my stored data from it it doesn't work.
Here is my code:
This is where I start the session and set the variables:
session_name("user");
session_start();
if ($groups != false) {
$_SESSION['groups'] = $groups->fetch_all(MYSQLI_ASSOC);
}
if ($dateformat != false) {
$_SESSION['dateformat'] = $dateformat;
}
$_SESSION['user_id'] = $row[0];
$_SESSION['user_firstname'] = $firstname;
$_SESSION['user_lastname'] = $lastname;
This is where I try to get my variables:
session_start();
if (isset($_SESSION['user_firstname'])) {
echo $_SESSION['user_firstname'];
}
Note: The page where I try to get the session data is my navbar/header it is only used with an php include statement.
It could be that $firstname is failing to be set. Try changing $_SESSION['user_firstname'] = $firstname; for example, to $_SESSION['user_firstname'] = "TEST"; and see if it stores that. If so, you're not giving $firstname a value.

PHP Session not setting

I have a PHP page and session, i started session on top of every site, but this isn't working.
I'm setting session (I'm setting class into session) with
}else if(isset($_POST['username']) and isset($_POST['password'])){
$account = new Account;
$password = hash('sha256', $_POST['password']);
$account->setTheAccount($_POST['username'],$password);
$acc_data = $account->getDatabaseAccounts('root','','schoolpage','localhost','accounts');
$acc_status = $account->isAccountTrue();
if ($acc_status==true){
$_SESSION['account'] = $account;
echo 'true';
header('Location:panel.php');
}else{
echo 'false';
}
}
and accessing it by:
if (isset($_SESSION['account'])){
$account = $_SESSION['account'];
if ($account->isAccountTrue() == true){
echo 'XD';
}
}
but it doesnt work.
I haven't idea why session not working.
Account class
class Account{
private $acc_data,$username,$password;
function setTheAccount($usernamei, $passwordi){
$this->username = $usernamei;
$this->password = $passwordi;
}
function getDatabaseAccounts($dbUser,$dbPassword,$dbName,$dbHost, $dbTable){
$pdo = new PDO('mysql:host='.$dbHost.';dbname='.$dbName, $dbUser, $dbPassword);
$this->acc_data = $pdo->query('SELECT * FROM `'.$dbTable.'`');
}
function isAccountTrue(){
$acc_status=false;
foreach ($this->acc_data as $i) {
if ($i['username'] == $this->username and $i['password'] == $this->password){
$acc_status = true;
}
}
return $acc_status;
}
function isUserLogged(){
}
}
Account class var dump
truearray(2) { ["login"]=> bool(true) ["account"]=> object(Account)#1 (3) { ["acc_data":"Account":private]=> object(PDOStatement)#3 (1) { ["queryString"]=> string(24) "SELECT * FROM `accounts`" } ["username":"Account":private]=> string(5) "admin" ["password":"Account":private]=> string(64) "4813494d137e1631bba301d5acab6e7bb7aa74ce1185d456565ef51d737677b2" } }
To store an object in $_SESSION you have to serialize it, then deserialize it to call the method ->isAccountTrue(), otherwise just store the result:
$_SESSION['accountValid']=$account->isAccountTrue();
...
if($_SESSION['accountValid']===true){
// do stuff
}
Put
error_reporting(-1);
ini_set('display_errors', true);
on top of the page to enable the php errors, and you will see that you can't serialize a resource, PDO instances, PDOStatement, etc. into session.
You can't serialize Account's $acc_data, since it's an instance of PDOStatement. You cannot serialize or unserialize PDOStatement instances.
Change
$this->acc_data = $pdo->query('SELECT * FROM `'.$dbTable.'`');
to
$this->acc_data = $pdo->query('SELECT * FROM `'.$dbTable.'`')->fetchAll();
then delete your session and retry.

Session variable inside a function parameter? (API CALLBACK)

Back story: Basically I'm trying to make a BTC api & to do this I need to basically use the ($custom inside of it) as i need to parse the variable $_SESSION['username'] onto my callback file to validate the user. I'm truly stuck here.
function getAddress($address, $callback, $_SESSION["username"], $secret)
{
$username = $_SESSION['username'];
$root_url = 'https://blockchain.info/api/receive';
$parameters = 'method=create&address=' . $address .'&callback='. urlencode($callback);
$callback = $callback.'?custom='.$username.'&secret='.$secret;
$response = file_get_contents($root_url . '?' . $parameters);
$object = json_decode($response);
return $object->input_address;
}
I know that I can't just put the variable $_SESSION['username'] there however, I'm not 100% sure how to do this: callback file:
$confirmation_level = 4;
$real_secret = 'ZzsMLGKe162CfA5EcG6j'; //Your Secret Key
$address = 'address'; //Your Bitcoin Address
$username = $_GET['custom'];
$input_address = $_GET['input_address'];
$transaction_hash = $_GET['transaction_hash'];
$input_transaction_hash = $_GET['input_transaction_hash'];
$value_in_satoshi = $_GET['value'];
$value_in_btc = $value_in_satoshi / 100000000;
//skipping to validate part
$btcpaidupdate = $odb ->prepare("UPDATE `users` SET paid=1 WHERE `username` = '$username'");
$btcpaidupdate ->execute();
So as you can see I'm completely stuck on how to parse the actual variable onto the callback api file.

mysqli connection not working inside function? [duplicate]

This question already has answers here:
Executing mysqli_query inside a function
(2 answers)
Closed 7 years ago.
I'm having some problems performing a mysql query inside a php function. The error I am getting is
Notice: Undefined variable: link in C:\path\api\inc\restFunctions.php on line 16
There are several files calling each other so I will attempt to outline the necessary information.
URL Accessed:
localhost/serverList/api/rest.php?action=allServers
serverList/api/rest.php
<?php
include 'inc/restFunctions.php';
$possibleCalls = array('allServers','allEnvs','allTypes','false');
if(isset($_GET['action'])){
$action = $_GET['action'];
}
else{
$action = 'false';
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers();
break;
case 'allEnvs':
$return = allEnvs();
break;
case 'allTypes':
$return = allTypes();
break;
case 'false':
$return = falseReturn();
break;
}
}
serverList/api/inc/restFunctions.php
<?php
include ('inc/config.php');
function allServers(){
$serverInfoQuery = "SELECT * FROM servers"
$allServerResults = $link->query($serverInfoQuery);
$json = array();
while($row = $allServerResults->fetch_assoc()){
$json[]['serverID'] = $row['serverID'];
$json[]['environment'] = $row['environment'];
$json[]['type'] = $row['type'];
$json[]['serverIP'] = $row['serverIP'];
$json[]['serverDescription'] = $row['serverDescription'];
$json[]['serverCreatedBy'] = $row['serverCreatedBy'];
$json[]['serverCreatedDtTm'] = $row['serverCreatedDtTm'];
$json[]['serverUpdatedBy'] = $row['serverUpdatedBy'];
$json[]['serverUpdatedDtTm'] = $row['serverUpdatedDtTm'];
}
$jsonResults = json_encode($json);
return $jsonResults;
}
?>
serverList/api/inc/config.php
<?php
$host = 'localhost';
$user = 'userName';
$password = 'password';
$database = 'database';
$link = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
?>
I have verified that the query being called works. I also verified that the connection info (masked above) works by using a different page of this software that queries the db.
I'm assuming I must have missed a quote or paren somewhere, but I'm baffled as to where it might be.
The problem is with PHP variable scoping. Add this line inside of allServers() function before you refer to the $link variable for the first time:
global $link;
See more here:
http://php.net/manual/en/language.variables.scope.php
In my opinion using global variables is not a good solution. You might override $link ($link is rather usual name for a variable you may be using for another purposes) variable in some scope by accident, resulting in lot's of confusion and difficult debugging.
Just pass it as a function parameter - much cleaner and easier to read:
function AllServers($link) {
$serverInfoQuery = "SELECT * FROM servers";
$allServerResults = $link->query($serverInfoQuery);
//More PHP code
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers($link);
break;
}
}
To be honest, even better solution would be using some generic classes/functions to establish your mysql connection like so:
class DB {
private static $link = null;
public static function getConnectionResource() {
//In that way we "cache" our $link variable so that creating new connection
//for each function call won't be necessary
if (self::$link === null) {
//Define your connection parameter here
self::$link = new mysqli($host, $user, $password, $database);
}
return self::$link;
}
}
function getAllServers() {
$link = DB::getConnectionResource();
//Preform your query and return results
}
Use global variable
function allServers(){
global $link
...
...
...
... your code follows

Underfind index in session

I try to load a session as I want with me into my handler. But the line 8 says that "during the find index" what is the error in my controller? It is a user name that I want to use a database to retrieve the id of the person.
Controller:
<?php
require_once ("View/PersonInfoView.php");
require_once ("Handler/UserHandler.php");
class PersonInfoController{
public function DoPersonInfo(){
$Personinfoview = new PersonInfoView();
$UserHandler = new UserHandler();
$PK = $UserHandler->GetUserID($_SESSION['Person']);
$Person_array = $UserHandler->ListPerson($PK);
$Personinfoview->Personbox($Person_array);
}
}
I set Session :
<?php
require_once ("Handler/Userhandler.php");
require_once ("Controller/LoginController.php");
class DologinHandler{
public function Login(){
if(isset($_REQUEST['is_ajax']))
{
$LoginController = new LoginController();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$_SESSION['Person'] = $username;
$UserHandler = new UserHandler();
$sign = $UserHandler -> controllDB($username,$password);
if($sign == true)
{
echo 'success';
return true;
}
else
{
echo 'error';
return false;
}
}
}
}
$loginclass = new DologinHandler();
$loginclass->Login();
I'm guessing your $_REQUEST doesn't contain the key Person. Try doing a var_dump() on $_REQUEST to see what it contains.
Other than that, I suggest you implement some kind of error handeling when calling $UserHandler->GetUserID()
For instance.
try {
$PK = $UserHandler->GetUserID($_SESSION['Person']);
} catch(Exception $e) {
echo($e->getMessage());
}
Read about exceptions.

Categories