Load database value with function - php

I didn't see any topic like this so I posted a new one.
First of all, I'm sorry about my bad English.
I want an public function who can storage in a global variable a value from database, and with that value the php script select the website templates. Can you help me?
private $page_title = null;
private $body_title = null;
private $body_content = null;
private $template = null;
private $settings = array();
private $file_template = 'content';
private $path = 'templates/';
private $parse_page = false;
global $template2;
public function GetHASH()
{
return $this->hash;
}
function Tema()
{
global $db,$user_class;
if($user_class->authorized)
{
$row = $db->sql("SELECT * FROM `ucp_users` WHERE `user_hash` = '".$this->GetHASH()."'");
$array = $db->get_array($row);
$template2 = $array['template'];
}
else
{
$template2 = '1';
}
return $template2;
}
function __construct() {
switch($template2) {
default:
{
$template_name = 'dsa/';
$template2 = 1;
}
break;
case 0: $template_name = 'lsrp/';
break;
case 1: $template_name = 'dsa/';
break;
}
$this->path = $this->path.''.$template_name;
}
Thank you.

When you instantiate your class, the constructor is called, at this time your tema method has not been invoked yet since it cannot be called without an instance. One solution would be to call your tema method in your constructor like this :
function __construct() {
$template2 = this->tema();
switch($template2) {
default:
{
$template_name = 'dsa/';
$template2 = 1;
}
break;
case 0: $template_name = 'lsrp/';
break;
case 1: $template_name = 'dsa/';
break;
}
$this->path = $this->path.''.$template_name;
}

Related

Exception 'Symfony\Component\Debug\Exception\FatalThrowableError' with message 'Call to undefined method getFeedsEntity()' i

Exception 'Symfony\Component\Debug\Exception\FatalThrowableError' with message 'Call to undefined method Perform\Feeds\Data\Article\Entity::getFeedsEntity()' in /var/www/sportingnews/releases/6.12.0-go/app/Models/Data/AdobeDTM/Model.php:94
I have tried in previous versions and it is working fine in the previous versions. Following is the line throwing error:
$author = $this->author->withArticle($article->getFeedsEntity()); Can anybody help why it is throwing error?
<?php
namespace App\Models\Data\AdobeDTM;
use App\Services\Article\Author;
use Illuminate\Routing\Router;
use Perform\Laravel\Locales\Service as LocalesService;
class Model
{
private $author;
private $localesService;
private $router;
public function __construct(
Author $author,
LocalesService $localesService,
Router $router
) {
$this->author = $author;
$this->localesService = $localesService;
$this->router = $router;
}
public function getNbaAdobeDtmSrc() :string
{
$localeToSrcMap = [
'au' => '//assets.adobedtm.com/1d1f22b7fbd1c6b82b92f8fffd66868071b86080/satelliteLib-7a2318cde68759d4f6b8ae79f4ac6cefe8d9584f.js',
'jp' => '//assets.adobedtm.com/1d1f22b7fbd1c6b82b92f8fffd66868071b86080/satelliteLib-18b8a632d390a5d9e96a3e41b7d99d5138b2f811.js',
];
$locale = $this->localesService->getLocale();
$src = $localeToSrcMap[$locale] ?? '';
if (empty($src)) {
throw new \Exception("The AdobeDTM head tag's src attribute is not configured for locale: $locale.");
}
return $src;
}
public function getDigialData($pageModel): array
{
$dataAttributes = $this->getDataAttributesByPage($pageModel);
return $dataAttributes->getValues();
}
private function getDataAttributesByPage($pageModel)
{
if (get_class($pageModel) == \App\Models\Pages\Error\Model::class) {
return new \App\Models\Data\AdobeDTM\DataAttributes\NullModel($this->localesService);
}
switch ($this->router->currentRouteName()) {
case 'sectionFront':
return new \App\Models\Data\AdobeDTM\DataAttributes\SectionFront($this->localesService);
break;
case 'sectionArchive':
return new \App\Models\Data\AdobeDTM\DataAttributes\Archive($this->localesService);
break;
case 'article':
$article = $pageModel->getArticle();
$meta = $pageModel->getTagNames();
$author = $this->author->withArticle($article->getFeedsEntity());
return new \App\Models\Data\AdobeDTM\DataAttributes\Article(
$this->localesService,
$article->getHeadline(),
$article->getArticleId(),
$author->getName(),
implode(',', $meta)
);
break;
case 'videoHubSport':
$videoTitle = $pageModel->getCurrentVideo()->title;
return new \App\Models\Data\AdobeDTM\DataAttributes\VideoHub($this->localesService, $videoTitle);
break;
case 'videoHubVideo':
$videoTitle = $pageModel->getCurrentVideo()->title;
return new \App\Models\Data\AdobeDTM\DataAttributes\VideoDetail($this->localesService, $videoTitle);
break;
case 'gallery':
$article = $pageModel->getArticle();
$meta = $pageModel->getTagNames();
return new \App\Models\Data\AdobeDTM\DataAttributes\Gallery(
$this->localesService,
$article->headline,
$article->id,
implode(',', $meta)
);
break;
case 'slideList':
$article = $pageModel->getArticle();
$meta = $pageModel->getTagNames();
$author = $this->author->withArticle($article->getFeedsEntity());
return new \App\Models\Data\AdobeDTM\DataAttributes\Slidelist(
$this->localesService,
$article->headline,
$article->id,
$author->getName(),
implode(',', $meta)
);
break;
default:
return new \App\Models\Data\AdobeDTM\DataAttributes\NullModel($this->localesService);
}
}
}

Unable to __set() a protected var

I am trying to get the script below on __set() to update the protected var.
I want this variable to be available to everyone, not just for one instance of the class object.
So far I can only get it to work for one instance, not globally.
class SessionClass
{
protected $ssnuid = 11;
protected $paccid = 11;
protected $authkey = 11;
public function __set($name, $value){
switch ($name) {
case 'ssnuid':
$this->$ssnuid = $value;
echo $ssnuid;
break;
case 'paccid':
$this->$paccid = $value;
echo $paccid;
break;
case 'authkey':
$this->$authkey = $value;
echo $authkey;
break;
}
}
public function __get($name){
return $this->name;
}
// END CLASS
} $session = new SessionClass;
$session->ssnuid = 20;
echo $session->ssnuid;
How can I achieve this?
*Newb here so please be kind. Thanks.

Accessing $_SESSION / $_GET / ... with dynamic variable

I have a class that takes care of all the user-related data.
In one of my methods i want to access $_SESSION / $_GET, $_POST, any $_...
via a dynamic var like following (in _unset method):
class Userdata
{
...
const knownSources = ['post', 'get', 'cookie', 'session', 'files'];
private $post = [];
private $get = [];
private $cookie = [];
private $session = [];
private $files = [];
...
private function __construct()
{
$this->post = $this->secureVars($_POST);
$this->get = $this->secureVars($_GET);
$this->cookie = $this->secureVars($_COOKIE);
...
}
public static function getInstance(){...}
public static function secureVars($inputVar, $asObject = true, $acceptHTML = false){...}
public static function _unset($dataSource, $key)
{
$self = self::getInstance();
if (in_array(strtolower($dataSource), self::knownSources))
{
// Here I want to unset the variable in $_SESSION[$key] for instance, but 'SESSION' can be whichever of knownSources array.
print_r([
${'_SESSION'},
${'_' . 'SESSION'},
${'_' . strtoupper($dataSource)}
]);
...
}
}
}
Any idea why ${'_SESSION'} works but not ${'_' . 'SESSION'}?
And how to perform my goal: ${'_' . strtoupper($dataSource)}?
Thanks for your help!
[EDIT]
AFTER SUGGESTIONS, I came to this:
switch($dataSource)
{
case 'session':
$target = $_SESSION;
break;
case 'post':
$target = $_POST;
break;
case 'get':
$target = $_GET;
break;
case 'cookie':
$target = $_COOKIE;
break;
case 'files':
$target = $_FILES;
break;
}
unset($self->$dataSource->$key);
unset($target[$key]);
[EDIT]
AFTER REALISING IT STILL WON'T WORK, I - sadly - opt for:
switch($dataSource)
{
case 'session':
unset($_SESSION[$key]);
break;
case 'post':
unset($_POST[$key]);
break;
case 'get':
unset($_GET[$key]);
break;
case 'cookie':
unset($_COOKIE[$key]);
break;
case 'files':
unset($_FILES[$key]);
break;
}
unset($self->$dataSource->$key);
Any smarter suggestion much appreciated :)
Try this:
//Url
//?dangerous=yes&safe=keep
class MyClass {
public static function _unset($datasource, $key) {
global $$datasource;
unset(${$datasource}[$key]);
}
}
MyClass::_unset('_GET', 'dangerous');
//Test
print_r($_GET);
You are missing the global keyword.

Setting PHP variable to class member in a Pass-By-Reference Fails

I am passing a variable by reference to a class method with the intention that it will be set to a member of that same class (based on a selector to the function). Although this doesn't appear to violate the rules of PHP's deprecated call-time pass-by-reference, I must be missing something, because it doesn't work.
I've dumbed down my code to illustrate the issue:
<?php
class Database
{
static $USER_TABLE = 1;
static $INVOICE_TABLE = 2;
static $PRODUCT_TABLE = 3;
var $users;
var $invoices;
var $products;
function __construct()
{
$this->users []= array ('id'=>0, 'first_name'=>'John', 'last_name'=>'Doe');
$this->products []= array('id'=>0, 'user_id'=>'0', 'printer'=>'HP','computer'=>'Toshiba');
$this->invoices []= array('id'=>0, 'user_id'=>'0', 'total_items'=>2, 'total_cost'=>700);
}
function getTable($table_name, &$table)
{
switch ($table_name)
{
case Database::$USER_TABLE: $table = $this->users; break;
case Database::$INVOICE_TABLE: $table = $this->invoices; break;
case Database::$PRODUCT_TABLE: $table = $this->products; break;
}
}
function addEntry($table_name, $info_array)
{
$this->getTable($table_name, $table); // THIS FAILS! WHY?
//$table = &$this->users; // THIS WORKS
if ($table !== null)
{
$id = 0;
if (count($table))
$id = ((int)$table[count($table)-1]['id'])+1;
$entry['id'] = $id;
foreach ($info_array as $k => $v)
{
$entry [$k]= $v;
}
$table []= $entry;
}
}
}
$db = new Database;
$db->addEntry(Database::$USER_TABLE, array('first_name'=>'Jane', 'last_name'=>'Plain'));
var_dump($db);
?>
The alternative is just to take the switch case out of getTable(...) and paste that to the top of all of my functions that would have called it, but that type of code duplication is not desirable.
Any insight is appreciated!
It'd be a lot easier just to have your getTable actually return a table:
function getTable($table_name)
{
switch ($table_name)
{
case Database::$USER_TABLE: return $this->users; break;
case Database::$INVOICE_TABLE: return $this->invoices; break;
case Database::$PRODUCT_TABLE: return $this->products; break;
}
}
And then just call the following:
$table = $this->getTable($table_name);

Logger Object - Variable Scope - access to Class/Function/etc

So I want to find the best method of allowing my Logger class to access any part of the script either another class/function/etc... How would I do this? How do I make it global.
Could I do something like this:
Logger::info('Add message like this?');
Calling script: calling.php
require_once('Logger.class.php'); // Just adding the class initializes the Logger Object
require_once('Another.class.php');
require_once('Functions.php');
$logEntry->info("Log info");
$logEntry->error("Log error");
$logEntry->warning("Log warning");
$logEntry->notice("Log notice");
$logEntry->enableDebug(); // prints debug to log
$logEntry->debug("Log debug enabled");
$logEntry->disableDebug();
$logEntry->debug("Log debug disabled"); // will not print to log
$another_obj = new Another(); // want the Logger to have access inside this class
More(); // want the Logger to have access inside this function
Another.class.php
class Another {
private $var;
// I want to add the Logger here
$logEntry->info("Another Log");
// More code here it's just an example ...
}
Functions.php
function More() {
// I want to add the Logger here
$logEntry->info("More Log");
}
Here is the Logger.class.php script
<?php
//Define Constants
define("LOG_FILE_DIRECTORY", "/var/www/logs");
ini_set("memory_limit","128M"); // Logger class is taking up memory
class Logger {
private $log_file_directory = LOG_FILE_DIRECTORY;
private $first_run; // Flag to add line break at the beginning of script execution
private $calling_script; // Base name of the calling script
private $log_file; // log file path and name
private $log_entry; // information to be logged
private $log_level; // Log severity levels: error, warning, notice, debug, info
private $fh; // File handle
private $file_name; // File path and name
private $file_parts; // Array of $file_name
private $script_name; // Script Name
private $script_parts; // Array of $script_name
private $line_number_arr; // Line number of where the logging event occurred
private $debug_flag; // Set to true if you want to log your debug logger
function __construct() {
$this->first_run = true;
$this->debug_flag = false;
$this->calling_script = '';
$this->log_file = '';
$this->log_entry = '';
$this->log_level = '';
$this->fh = '';
$this->file_name = '';
$this->file_parts = '';
$this->script_name = '';
$this->script_parts = '';
$this->line_number_arr = '';
}
/**
* #enableDebug
*/
public function enableDebug() {
$this->debug_flag = true;
}
/**
* #disbaleDebug
*/
public function disableDebug() {
$this->debug_flag = false;
}
/**
* #info
*/
public function info($message) {
$this->log_level = 'info';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
/**
* #error
*/
public function error($message) {
$this->log_level = 'error';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
/**
* #warning
*/
public function warning($message) {
$this->log_level = 'warning';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
/**
* #notice
*/
public function notice($message) {
$this->log_level = 'notice';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
/**
* #debug
* must add the below to the script you wish to debug
* define("DEBUG", true); // true enables, false disables
*/
public function debug($message) {
if($this->debug_flag) {
$this->log_level = 'debug';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
}
private function addEntry($message) {
$this->calling_script = $this->getScriptBaseName();
$this->log_file = $this->log_file_directory."/".$this->calling_script.".log";
$this->fh = fopen($this->log_file, 'a') or die("Can't open log file: ".$this->log_file);
if($this->first_run) {
$this->log_entry = "\n[" . date("Y-m-d H:i:s", mktime()) . "][line:".$this->line_number_arr[0]['line']."|".$this->log_level."]:\t".$message."\n";
} else {
$this->log_entry = "[" . date("Y-m-d H:i:s", mktime()) . "][line:".$this->line_number_arr[0]['line']."|".$this->log_level."]:\t".$message."\n";
}
fwrite($this->fh, $this->log_entry);
fclose($this->fh);
$this->first_run = false;
}
/**
* return the base name of the calling script
*/
private function getScriptBaseName() {
$this->file_name = $_SERVER["SCRIPT_NAME"];
$this->file_parts = explode('/', $this->file_name);
$this->script_name = $this->file_parts[count($this->file_parts) - 1];
$this->script_parts = explode('.', $this->script_name);
// If file doesn't exists don't add line break
if(!file_exists($this->script_parts[0].".log")) {
$this->first_run = false;
}
return $this->script_parts[0];
}
}
// Start log instance
$logEntry = new Logger();
?>
You could implement it as a class full of static functions, e.g.:
class Logger {
protected $logfile = null;
public static load() {
self::$logfile = fopen('error.log', 'a');
}
public static info($msg) {
if(self::$logfile == null)
self::load();
fwrite(self::$logfile, $msg);
}
}
and then use it with Logger::info("My message..");. Another common method of doing this is using a singleton class, so that you can only create a single object of "Logger" and retrieve it using e.g. Logger::getInstance()->logInfo("My message");.
In your case (as you already implemented Logger as a normal class) I would make the __construct private and implement the class as a singleton. It's not possible to make $logEntry globally available. Your code would become:
<?php
//Define Constants
define("LOG_FILE_DIRECTORY", "/var/www/logs");
ini_set("memory_limit","128M"); // Logger class is taking up memory
class Logger {
private $log_file_directory = LOG_FILE_DIRECTORY;
private $first_run; // Flag to add line break at the beginning of script execution
private $calling_script; // Base name of the calling script
private $log_file; // log file path and name
private $log_entry; // information to be logged
private $log_level; // Log severity levels: error, warning, notice, debug, info
private $fh; // File handle
private $file_name; // File path and name
private $file_parts; // Array of $file_name
private $script_name; // Script Name
private $script_parts; // Array of $script_name
private $line_number_arr; // Line number of where the logging event occurred
private $debug_flag; // Set to true if you want to log your debug logger
private static $instance = null;
private function __construct() {
$this->first_run = true;
$this->debug_flag = false;
$this->calling_script = '';
$this->log_file = '';
$this->log_entry = '';
$this->log_level = '';
$this->fh = '';
$this->file_name = '';
$this->file_parts = '';
$this->script_name = '';
$this->script_parts = '';
$this->line_number_arr = '';
}
public static function getInstance() {
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
/**
* #enableDebug
*/
public function enableDebug() {
$this->debug_flag = true;
}
/**
* #disbaleDebug
*/
public function disableDebug() {
$this->debug_flag = false;
}
/**
* #info
*/
public function info($message) {
$this->log_level = 'info';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
/**
* #error
*/
public function error($message) {
$this->log_level = 'error';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
/**
* #warning
*/
public function warning($message) {
$this->log_level = 'warning';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
/**
* #notice
*/
public function notice($message) {
$this->log_level = 'notice';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
/**
* #debug
* must add the below to the script you wish to debug
* define("DEBUG", true); // true enables, false disables
*/
public function debug($message) {
if($this->debug_flag) {
$this->log_level = 'debug';
$this->line_number_arr = debug_backtrace();
$this->addEntry($message);
}
}
private function addEntry($message) {
$this->calling_script = $this->getScriptBaseName();
$this->log_file = $this->log_file_directory."/".$this->calling_script.".log";
$this->fh = fopen($this->log_file, 'a') or die("Can't open log file: ".$this->log_file);
if($this->first_run) {
$this->log_entry = "\n[" . date("Y-m-d H:i:s", mktime()) . "][line:".$this->line_number_arr[0]['line']."|".$this->log_level."]:\t".$message."\n";
} else {
$this->log_entry = "[" . date("Y-m-d H:i:s", mktime()) . "][line:".$this->line_number_arr[0]['line']."|".$this->log_level."]:\t".$message."\n";
}
fwrite($this->fh, $this->log_entry);
fclose($this->fh);
$this->first_run = false;
}
/**
* return the base name of the calling script
*/
private function getScriptBaseName() {
$this->file_name = $_SERVER["SCRIPT_NAME"];
$this->file_parts = explode('/', $this->file_name);
$this->script_name = $this->file_parts[count($this->file_parts) - 1];
$this->script_parts = explode('.', $this->script_name);
// If file doesn't exists don't add line break
if(!file_exists($this->script_parts[0].".log")) {
$this->first_run = false;
}
return $this->script_parts[0];
}
}
?>
You would then use your class globally using Logger::getInstance()->info($msg);

Categories