php Class calling a function inside another function error - php

I have the following class with few functions inside. I'm getting an error when i call the get_dir_size() inside the Diskspace() function. It's not recognizing it. What am i doing wrong. This code is for creating an expressionengine plugin.
Fatal error: Call to undefined function get_dir_size()
class DiskSpace
{
public $return_data = "";
public function Diskspace()
{
$this->EE =& get_instance();
$dir_name = $_SERVER['DOCUMENT_ROOT']."/userfiles/";
/* 1048576 bytes == 1MB */
$total_size= round((get_dir_size($dir_name) / 1048576),2) ;
$this->return_data = $total_size;
}
public function get_dir_size($dir_name){
$dir_size =0;
if (is_dir($dir_name)) {
if ($dh = opendir($dir_name)) {
while (($file = readdir($dh)) !== false) {
if($file !="." && $file != ".."){
if(is_file($dir_name."/".$file)){
$dir_size += filesize($dir_name."/".$file);
}
/* check for any new directory inside this directory */
if(is_dir($dir_name."/".$file)){
$dir_size += get_dir_size($dir_name."/".$file);
}
}
}
}
}
closedir($dh);
return $dir_size;
}
}

Change the line that calls get_dir_size($dir_name) to :-
$total_size= round(($this->get_dir_size($dir_name) / 1048576),2) ;
There are a few more issues with this code
What is this ? $this->EE = & get_instance();
and also you will get errors when you execute closedir($dh); if the if statement that it is declared in is not executed.

Remember when you call objects own function inside the object, use the $this pointer variable.
$total_size= round((get_dir_size($dir_name) / 1048576),2) ;
Change to
$total_size= round(($this->get_dir_size($dir_name) / 1048576),2) ;
Would be also good if you told us which line the error is happening at. Would be also nice to see the full error log.

Related

Trouble with undefined variable in laravel

I have my APIrest in Laravel 5.
I'm trying to upload files.
This is my controller :
public function makeFile(Request $request)
{
if(isset($request->files) && is_array($request->files)) {
$fileArray=array();
foreach($request->files as $key=>$fileEntity) {
$file= new File();
$file->file=$fileEntity['file'];
$file->shipment_id=$fileEntity['shipment_id'];
$file->user_id=$fileEntity['user_id'];
$file->date=date('Y,m,d,G,i,s');
$file->fileName=$fileEntity['fileName'];
$file->fileType=$fileEntity['fileType'];
$file->status=$fileEntity['status'];
$file->save();
array_push($fileArray, $file);
}
// return response()->json($fileArray);
}
(line 132 the one of the error) return response()->json($fileArray);
}
In the frontend (angularjs) when i upload a file it throws this error
ErrorException in ShipmentController.php line 132: Undefined variable:
fileArray
Why this is happening?
You have to declare the $fileArray=array(); outside the first if. If the first if doesn't evaluate true, the variable isn't set.
You declared $fileArray variable inside if statement it works like local variable for this statement.
Solution:
public function makeFile(Request $request)
{
$fileArray = [];
if (isset($request->files) && is_array($request->files)) {
foreach ($request->files as $key => $fileEntity) {
$file= new File();
$file->file=$fileEntity['file'];
$file->shipment_id=$fileEntity['shipment_id'];
$file->user_id=$fileEntity['user_id'];
$file->date=date('Y,m,d,G,i,s');
$file->fileName=$fileEntity['fileName'];
$file->fileType=$fileEntity['fileType'];
$file->status=$fileEntity['status'];
$file->save();
$fileArray[] = $file;
}
}
return response()->json($fileArray);
}

Widget in CodeIgniter 3

For a dashboard-app, I want to create a widget-component in my CI3-project. I found a similar question: How to create a widget system in Codeigniter, but it seems that this is either outdated or just not usable for CI3. Even the link with the "more information" results in a 404.
I googled that of course, but didn't find anything useful. One post was from 2013, which showed that example von the CI2 base.
However, maybe this plugin still works and I have an error in my setup.
I placed a file "Widget.php" in
/application/third_party/
with the following content:
class Widget
{
public $module_path;
function run($file) {
$args = func_get_args();
$module = '';
/* is module in filename? */
if (($pos = strrpos($file, '/')) !== FALSE) {
$module = substr($file, 0, $pos);
$file = substr($file, $pos + 1);
}
list($path, $file) = Modules::find($file, $module, 'widgets/');
if ($path === FALSE) {
$path = APPPATH.'widgets/';
}
Modules::load_file($file, $path);
$file = ucfirst($file);
$widget = new $file();
$widget->module_path = $path;
return call_user_func_array(array($widget, 'run'), array_slice($args, 1));
}
function render($view, $data = array()) {
extract($data);
include $this->module_path.'views/'.$view.EXT;
}
function load($object) {
$this->$object = load_class(ucfirst($object));
}
function __get($var) {
global $CI;
return $CI->$var;
}
}
In my application/widgets-folder, I have a file called News.php.
<?php
class News extends Widget
{
function run() {
die('here');
}
}
In application/libraries/ I placed a file widgetlib.php :
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class widgetlib {
function __construct() {
include(APPPATH . '/third_party/Widget.php');
}
}
and finally, in my view:
<?php widget::run("News"); ?>
Then I checked my autoloader-class in application/config/autoload.php:
$autoload['libraries'] =
'session',
'database',
'widgetlib'
);
This results in:
A PHP Error was encountered
Severity: Error
Message: Class 'Modules' not found
Filename: third_party/Widget.php
Line Number: 20
and
Severity: Runtime Notice
Message: Non-static method Widget::run() should not be called statically, assuming $this from incompatible context
Filename: views/index.php

How to implement method pointers in PHP

Is there a way to implement method pointers in PHP?
I keep getting the following error:
Fatal error: Call to undefined function create_jpeg() in /Users/sky/Documents/images.php on line 175
This is line 175:
if ($this->ImageType_f[$pImageType]($pPath) != 0)
class CImage extends CImageProperties
{
private $Image;
private $ImagePath;
private $ImageType;
private function create_jpeg($pFilename)
{
if (($this->Image = imagecreatefromjepeg($pFilename)) == false)
{
echo "TEST CREATION JPEG\n";
echo "Error: ".$pFilename.". Creation from (JPEG) failed\n";
return (-1);
}
return (0);
}
private function create_gif($pFilename)
{
if (($this->Image = imagecreatefromgif($pFilename)) == false)
{
echo "Error: ".$pFilename.". Creation from (GIF) failed\n";
return (-1);
}
return (0);
}
private function create_png($pFilename)
{
if (($this->Image = imagecreatefrompng($pFilename)) == false)
{
echo "Error: ".$pFilename.". Creation from (PNG) failed\n";
return (-1);
}
return (0);
}
function __construct($pPath = NULL)
{
echo "Went through here\n";
$this->Image = NULL;
$this->ImagePath = $pPath;
$this->ImageType_f['JPEG'] = 'create_jpeg';
$this->ImageType_f['GIF'] = 'create_gif';
$this->ImageType_f['PNG'] = 'create_png';
}
function __destruct()
{
if ($this->Image != NULL)
{
if (imagedestroy($this->Image) != true)
echo "Failed to destroy image...";
}
}
public function InitImage($pPath = NULL, $pImageType = NULL)
{
echo "pPath: ".$pPath."\n";
echo "pImgType: ".$pImageType."\n";
if (isset($pImageType) != false)
{
if ($this->ImageType_f[$pImageType]($pPath) != 0)
return (-1);
return (0);
}
echo "Could not create image\n";
return (0);
}
}
Just call the method you need with $this->$method_name() where $method_name is a variable containing the method you need.
Also it is possible using call_user_func or call_user_func_array
What is callable is described here: http://php.net/manual/ru/language.types.callable.php
So assuming $this->ImageType_f['jpeg']' must be callable: array($this, 'create_jpeg').
Alltogether: call_user_func($this->ImageType_f[$pImageType], $pPath) is the way to do it.
Or if $this->ImageType_f['jpeg'] = 'create_jpeg':
$this->{$this->ImageType_f['jpeg']]($pPath);
Some documentation on functions I mentioned here:
http://us2.php.net/call_user_func
http://us2.php.net/call_user_func_array
Your problem is is line:
if ($this->ImageType_f[$pImageType]($pPath) != 0)
-since $this->ImageType_f[$pImageType] will result in some string value, your call will be equal to call of global function, which does not exists. You should do:
if ($this->{$this->ImageType_f[$pImageType]}($pPath) != 0)
-but that looks tricky, so may be another good idea is to use call_user_func_array():
if (call_user_func_array([$this, $this->ImageType_f[$pImageType]], [$pPath]) != 0)
I think you need to use this function call_user_func
In your case call will looks like
call_user_func(array((get_class($this), ImageType_f[$pImageType]), array($pPath));

My function works outside of the class but not from within the class

I feel like I'm missing something obvious here. I have a class as follows:
<?php
class files
{
public function getDirectoryList($directory)
{
// create an array to hold directory list
$results = array();
// create a handler for the directory
$handler = opendir($directory);
// open directory and walk through the filenames
while($file = readdir($handler))
{
// if the file isn't this directory or the parent, add it to the results.
if($file != "." && $file != "..")
{
$results[] = $file;
}
}
// tidy up: close the handler
closedir($handler);
//done
return $results;
}
}
?>
Now I have the class included into another file and I'm doing the following:
$fileListing = new files();
$fileListing->getDirectoryList('education');
I'm not getting any results back. If I take the function out of the class and put it in this file, I can get results by doing:
$fileListing = getDirectoryList('education');

Error When Calling Function

I searched forever trying to find an answer, but was ultimately stumped. I've been writing code to allow multiple bots to connect to a chat box. I wrote all the main code and checked it over to make sure it was all okay. Then when I got to calling the function needed to make it work, it gave me an error saying:
Notice: Undefined variable: ip in C:\wamp\www\BotRaid.php on line 40
And also an error saying:
Fatal Error: Cannot access empty property in C:\wamp\www\BotRaid.php
on line 40
( Also a screenshot here: http://prntscr.com/ckz55 )
<?php
date_default_timezone_set("UCT");
declare(ticks=1);
set_time_limit(0);
class BotRaid
{
public $ip="174.36.242.26";
public $port=10038;
public $soc = null;
public $packet = array();
##############################
# You can edit below this #
##############################
public $roomid="155470742";
public $userid = "606657406";
public $k = "2485599605";
public $name="";
public $avatar=;
public $homepage="";
##############################
# Stop editing #
##############################
public function retry()
{
$this->connect($this->$ip,$this->$port); //Line 40, where I'm getting the error now.
$this->join($this->$roomid);
while($this->read()!="DIED");
}
public function connect($ip, $port)
{
if($this->$soc!=null) socket_close($this->$soc);
$soc = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(!$this->$soc)$this->port();
if(!socket_connect($this->$soc,$this->$ip,$this->$port))$this->port();
}
public function port()
{
$this->$port++;
if($this->$port>10038) $this->$port=10038;
$this->retry();
}
public function join($roomid)
{
$this->send('<y m="1" />');
$this->read();
$this->send('<j2 q="1" y="'.$this->$packet['y']['i'].'" k="'.$this->$k.'" k3="0" z="12" p="0" c"'.$roomid.'" f="0" u="'.$this->$userid.'" d0="0" n="'.$this->$name.'" a="'.$this->$avatar.'" h="'.$this->$homepage.'" v="0" />');
$this->port();
$this->$roomid;
}
public function send($msg)
{
echo "\n Successfully connected.";
socket_write($this->$soc, $this->$msg."\0", strlen($this->$msg)+1);
}
public function read($parse=true)
{
$res = rtrim(socket_read($this->$soc, 4096));
echo "\nSuccessfully connected.";
if(strpos(strtolower($res), "Failed"))$this->port();
if(!$res) return "DIED";
$this->lastPacket = $res;
if($res{strlen($res)-1}!='>') {$res.=$this->read(false);}
if($parse)$this->parse($res);
return $res;
}
public function parse($packer)
{
$packet=str_replace('+','#più#',str_replace(' ="',' #=#"',$packet));
if(substr_count($packet,'>')>1) $packet = explode('/>',$packet);
foreach((Array)$packet as $p) {
$p = trim($p);
if(strlen($p)<5) return;
$type = trim(strtolower(substr($p,1,strpos($p.' ',' '))));
$p = trim(str_replace("<$type",'',str_replace('/>','',$p)));
parse_str(str_replace('"','',str_replace('" ','&',str_replace('="','=',str_replace('&','__38',$p)))),$this->packet[$type]);
foreach($this->packet[$type] as $k=>$v) {
$this->packet[$type][$k] = str_replace('#più#','+',str_replace('#=#','=',str_replace('__38','&',$v)));
}
}
}
}
$bot = new BotRaid; //This is where I had the error originally
$bot->retry();
?>
Line 40 is below the "Stop Editing" line. Anyone have any suggestions? Or perhaps need me to clear some things up?
You are accessing the properties of the class incorrectly.
The line:
$this->connect($this->$ip,$this->$port);
Should be:
$this->connect($this->ip, $this->port);
Since there was no local variable called $ip, your expression was evaluating to $this-> when trying to access the property since PHP lets you access properties and functions using variables.
For example, this would work:
$ip = 'ip';
$theIp = $this->$ip; // evaluates to $this->ip
// or a function call
$method = 'someFunction';
$value = $this->$method(); // evaluates to $this->someFunction();
You will have to change all the occurrences of $this->$foo with $this->foo since you used that notation throughout the class.
As noted in the comment by #Aatch, see the docs on variable variables for further explanation. But that is what you were running into accidentally.

Categories