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.
Related
I'm currently a beginner developer and have just started my first big project whilst I have spare time, What I'm trying to do is basically write variables to a html/tpl document, Which I have currently got working, Here is my code:
private function index(){
$username = 'MyUsername';
$onlineTime = 'MyOnlineTime';
$this->setParams('Username', $username); // $username Will be replaced by database queried results once completed.
}
And here is the setParams function.
function setParams($item1, $item2){
ob_start();
$theme = 'default';
include_once T . '/'.$theme.'/index.php'; // T . is defined at the beginning of the document.
if ((($html = ob_get_clean()) !== false) && (ob_start() === true))
{
echo preg_replace('~{(['.$item1.']*)}~i', ''.$item2.'', $html, 1);
}
}
And here is the coding inside the html/tpl document.
{username} has been online for {onlineTime} Hours
This is probably a very simple code for some of you but as this is my first attempt this is all I can do.
What I would like to do is have it so you can setParams as many times as you want without changing the $variable names like so:
private function index(){
$username = 'MyUsername';
$onlineTime = 'MyOnlineTime';
$this->setParams('Username',$username);
$this->setParams('OnlineTime', $onlineTime);
}
whilst keeping the setParams($item1, $item2)
But as you can imagine this just cuts the code completely. Does anyone know a solution to this problem? I've been searching all day without any real luck.
Thanks In Advance,
Ralph
I think what you need is a class with a static method;
<?php
class Params {
public static $params = array();
public static function setParam($key, $value) {
self::$params[$key] = $value;
}
public static function getParam($key) {
if (isset(self::$params[$key])) {
return self::$params[$key];
}
}
}
// Usage
// Set Username
Params::setParam("username", "JohnDoe");
Params::setParam("password", "12345");
echo Params::getParam("username");
echo Params::getParam("password");
I'm using custom class to connect to asterisk server via php.
Here it's code:
class Asterisk_ami
{
public $ini = array();
function __construct ()
{
$this->ini["con"] = false;
$this->ini["host"] = "127.0.0.1";
$this->ini["port"] = "****";
$this->ini["lastActionID"] = 0;
$this->ini["lastRead"] = array();
$this->ini["sleep_time"]=1.5;
$this->ini["login"] = "****";
$this->ini["password"] = "****";
}
function __destruct()
{
unset ($this->ini);
}
public function connect()
{
$this->ini["con"] = fsockopen($this->ini["host"], $this->ini["port"],$a,$b,10);
if ($this->ini["con"])
{
stream_set_timeout($this->ini["con"], 0, 400000);
}
}
public function disconnect()
{
if ($this->ini["con"])
{
fclose($this->ini["con"]);
}
}
public function write($a)
{
$this->ini["lastActionID"] = rand (10000000000000000,99999999900000000);
fwrite($this->ini["con"], "ActionID: ".$this->ini["lastActionID"]."\r\n$a\r\n\r\n");
$this->sleepi();
return $this->ini["lastActionID"];
}
public function sleepi ()
{
sleep($this->ini["sleep_time"]);
}
public function read()
{
$mm = array();
$b = array();
$mmmArray=array();
$k = 0;
$s = "";
$this->sleepi();
do
{
$s.= fread($this->ini["con"],1024);
sleep(0.005);
$mmm=socket_get_status($this->ini["con"]);
array_push($mmmArray, $mmm);
} while ($mmm['unread_bytes']);
$mm = explode ("\r\n",$s);
$this->ini["lastRead"] = array();
for ($i=0;$i<count($mm);$i++)
{
if ($mm[$i]=="")
{
$k++;
}
$m = explode(":",$mm[$i]);
if (isset($m[1]))
{
$this->ini["lastRead"][$k][trim($m[0])] = trim($m[1]);
}
}
unset ($b);
unset ($k);
unset ($mm);
unset ($mm);
unset ($mmm);
unset ($i);
unset ($s);
var_dump($mmmArray);
return $this->ini["lastRead"];
//return $s;
}
public function init()
{
return $this->write("Action: Login\r\nUsername: ".$this->ini["login"]."\r\nSecret: ".$this->ini["password"]."\r\n\r\n");
}
}
And here is testAsterisk.php where I try it.
include("./lib/asteriskAmi.php");
$a = new Asterisk_ami();
$a->connect();
if ($a->ini["con"])
{
$a->init();
$a->write("Action: GetConfig\r\nFilename: extensions.conf\r\n");
print_r($a->read());
$a->disconnect();
}
I want to get extension.conf config via ami. The problem is that I don't get full config. 16 last string are alwas missing. However when I check GetConfig via asterisk console it returns full config.
As you can see while cycle is interrupted when unread bytes of socket_get_status are 0, I checked them pushing in array and dumping it, and I can see that unread_bytes are actually 0. I tried changing sleep_time and different timeout parametres, the result was the same.
What else can I check? What can cause this mistake? May be I can use some other func?
Really, only proper solution I've found is to use PAMI, instead of custom class. It's more comfortable for using and anyway it gives me full content of extensions.conf.
I have written a php class to use in a small script to just run any query that I like from other scripts. This is NOT going to be used publicly or in production, and I'm aware of the huge security issue this poses!
I have done this as an excercise to see learn about classes etc... I seem to be having problems with one specific line in the code which is causing an error somewhere. I think it might be because I'm trying to return an array, and I think I haven't defined it properly in the class.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
This is the whole code.
<?php
class GetRandomRecord {
//Connection
public $CUDBName;
public $CUHost;
public $CUUser;
public $CUPassword;
public $in_SQL;
public $out_Resource;
public $CULink;
public $message;
public $errors = array(); // is this correct?
public $resultOfQuery = array(); // is this correct?
/****************************************************************/
public function setSQL($value){
$this->in_SQL = $value;
return $this->in_SQL;
}
/****************************************************************/
public function setConnectionString($db,$host,$user,$password){
$this->CUDBName = $db;
$this->CUHost = $host;
$this->CUUser = $user;
$this->CUPassword = $password;
}
/****************************************************************/
public function runSQL() {
$this->CULink = mysqli_connect( $this->CUHost , $this->CUUser , $this->CUPassword , $this->CUDBName);
if (mysqli_connect_errno()) {
$this->message = "Connection failed: ".mysqli_connect_error();
return $this->message;
}
$this->out_Resource = mysqli_query($this->in_SQL , $this->CULink);
if (!$this->out_Resource)
{
$this->errors['sql'] = $this->in_SQL;
$this->errors['eeDBName'] = $this->CUDBName;
$this->errors['eeLink'] = $this->CULink;
$this->errors['status'] = "false"; //There was a problem saving the data;
mysqli_close($this->CULink);
return json_encode($this->errors);
}
else
{
// success
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
mysql_close($this->CULink);
return $this->resultOfQuery;
} // if (!mysql_query( $CUDBName , $sql , $CULink))
}
/****************************************************************/
}//class
$recordGet = new getRandomRecord();
$recordGet->setConnectionString('databasename','localhost','username','password');
// select count from database
$tableName = "userList";
$countSQL = "select count(*) from $tableName";
$recordGet->setSQL($countSQL);
$result = $recordGet->runSQL();
print_r($result);
?>
Can you help me identify the problem?
EDIT: Actually I haven't got a specific error message. I have an HTTP Error 500 which usually means my code is duff, and I narrowed it down by commenting sections of code until I found the line that caused it.
You have an extra close-paren on line 64.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
The line should be:
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC);
I got an error while running my code, it says call to a member function getBallparkDetailsStartDate() on a non-object.
if($projectStatusId == ProjectStatusKeys::BALLPARK_ACTIVE) {
$ballpark = $this->ballparkDetailsHandler->getBallparkDetailsByProjectId($projectId);
$projectDetails["startdate"] = $ballpark->getBallparkDetailsStartDate();
$projectDetails["enddate"] = $ballpark->getBallparkDetailsEndDate();
$projectDetails["projectid"] = $projectId;
$projectDetails["name"] = $ballpark->getBallparkDetailsBookingRef();
$projectDetails["status"] = ProjectStatusKeys::BALLPARK_ACTIVE;
}
I got the error in this line: $projectDetails["startdate"] = $ballpark->getBallparkDetailsStartDate();
Here is my other code:
public function __construct($ballparkDetailsId, $project,
$ballparkDetailsBookingRef,
$ballparkDetailsStartDate, $ballparkDetailsEndDate,
$ballparkDetailsExpiryDate, $ballparkDetailsDescription,
$ballparkDetailsNotes) {
$this->ballparkDetailsId = $ballparkDetailsId;
$this->project = $project;
$this->ballparkDetailsBookingRef = $ballparkDetailsBookingRef;
$this->ballparkDetailsStartDate = $ballparkDetailsStartDate;
$this->ballparkDetailsEndDate = $ballparkDetailsEndDate;
$this->ballparkDetailsExpiryDate = $ballparkDetailsExpiryDate;
$this->ballparkDetailsDescription = $ballparkDetailsDescription;
$this->ballparkDetailsNotes = $ballparkDetailsNotes;
}
public function getBallparkDetailsId() {
return $this->ballparkDetailsId;
}
public function getProject() {
return $this->project;
}
public function getBankName() {
return $this->getProject()->getBankName();
}
public function getBankRef() {
return $this->getProject()->getBankRef();
}
public function getRegionName() {
return $this->getProject()->getRegionName();
}
public function getProjectStatusName() {
return $this->getProject()->getProjectStatusName();
}
public function getBallparkDetailsBookingRef() {
return $this->ballparkDetailsBookingRef;
}
public function getBallparkDetailsStartDate() {
return $this->ballparkDetailsStartDate;
}
public function getBallparkDetailsEndDate() {
return $this->ballparkDetailsEndDate;
}
public function getBallparkDetailsExpiryDate() {
return $this->ballparkDetailsExpiryDate;
}
public function getBallparkDetailsDescription() {
return $this->ballparkDetailsDescription;
}
public function getBallparkDetailsNotes() {
return $this->ballparkDetailsNotes;
}
public function getProjectId() {
return $this->getProject()->getProjectId();
}
public function getProjectStatusId() {
return $this->getProject()->getProjectStatusId();
}
}
?>
The last time I check this it ran well. But now I don't know what's wrong with this? Please help me find the error. Thanks.
Apparently
$ballpark = $this->ballparkDetailsHandler->getBallparkDetailsByProjectId($projectId);
is not returning a "ballpark" at all. Probably it is returning an error, or something like an empty array.
Try var_dump()'ing $ballpark immediately before the line that raises the error, and see what it contains (probably False, NULL, array() or something equally un-ballparky.
Then, inspect the ballparkDetailsByProjectId() function in the BallparkDetailsHandler.php file. At a guess, you might be passing an invalid (i.e. nonexistent, removed, etc.) $projectId.
Then you might rewrite the code with error checking:
if($projectStatusId == ProjectStatusKeys::BALLPARK_ACTIVE) {
$ballpark = $this->ballparkDetailsHandler->getBallparkDetailsByProjectId($projectId);
if (!is_object($ballpark))
trigger_error("Error: bad project ID: '$projectId': $ballpark",
E_USER_ERROR);
$projectDetails["startdate"] = $ballpark->getBallparkDetailsStartDate();
$projectDetails["enddate"] = $ballpark->getBallparkDetailsEndDate();
$projectDetails["projectid"] = $projectId;
$projectDetails["name"] = $ballpark->getBallparkDetailsBookingRef();
$projectDetails["status"] = ProjectStatusKeys::BALLPARK_ACTIVE;
}
Then in the BallparkDetailsHandler.php file you could modify this code:
// Prepare query or die
if (!($stmt = $this->mysqli->prepare($query))
return "Error in PREPARE: $query";
$stmt->bind_param("i", $projectId);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($ballparkDetailsBookingRef, $bankRef, $regionName,
$projectStatusId, $projectStatusName, $ballparkDetailsDescription,
$ballparkDetailsNotes, $ballparkDetailsStartDate, $ballparkDetailsEndDate,
$ballparkDetailsExpiryDate);
$stmt->fetch();
// If no data, then die
if(!$stmt->num_rows)
return "No data in DB for projectID '$projectId': $query";
// Should be clear sailing from here on. Actually I ought to check
// whether all these new() here do return anything sensible, or not
$bank = new Bank("", "", $bankRef, "");
$region = new Region("", $regionName, "");
$projectStatus = new ProjectStatus($projectStatusId, $projectStatusName);
$project = new Project($projectId, $bank, $region, $projectStatus);
return new BallparkDetails("", $project,
$ballparkDetailsBookingRef, $ballparkDetailsStartDate,
$ballparkDetailsEndDate, $ballparkDetailsExpiryDate,
$ballparkDetailsDescription, $ballparkDetailsNotes);
$ballpark clearly doesn't contain the object you think it does on the line with the error. In fact, it obviously doesn't contain an object at all.
This implies that the preceding line (which sets $ballpark) isn't working properly. It would appear that it's returning a value that is is not an object.
I can't tell what that value is -- it could be null, or it could be an integer, string, array, etc. But whatever it is, it isn't a ballpark object.
I suggest you look at your getBallparkDetailsByProjectId() method to find the source of this problem.
Let's say I have a class...
class A {
private $action;
private $includes;
public function __construct($action, $file) {
//assign fields
}
public function includeFile()
include_once($this->file);
}
$a = new A('foo.process.php', 'somefile.php');
$a->includeFile();
As you can see, includeFile() calls the include from within the function, therefore once the external file is included, it should technically be inside of the function from my understanding.
After I've done that, let's look at the file included, which is somefile.php, which calls the field like so.
<form action=<?=$this->action;?> method="post" name="someForm">
<!--moar markup here-->
</form>
When I try to do this, I receive an error. Yet, in a CMS like Joomla I see this accomplished all the time. How is this possible?
Update
Here's the error I get.
Fatal error: Using $this when not in object context in /var/www/form/form.process.php on line 8
Update 2
Here's my code:
class EditForm implements ISave{
private $formName;
private $adData;
private $photoData;
private $urlData;
private $includes;
public function __construct(AdData $adData, PhotoData $photoData, UrlData $urlData, $includes) {
$this->formName = 'pageOne';
$this->adData = $adData;
$this->photoData = $photoData;
$this->urlData = $urlData;
$this->includes = $includes;
}
public function saveData() {
$this->adData->saveData();
$this->photoData->saveData();
}
public function includeFiles() {
if (is_array($this->includes)) {
foreach($this->includes as $file) {
include_once($file);
}
} else {
include_once($this->includes);
}
}
public function populateCategories($parent) {
$categories = $this->getCategories($parent);
$this->printCategories($categories);
}
public function populateCountries() {
$countries = $this->getCountries();
$this->printCountries($countries);
}
public function populateSubCategories() {
//TODO
}
private function getCategories($parent) {
$db = patentionConnect();
$query =
"SELECT * FROM `jos_adsmanager_categories`
WHERE `parent` = :parent";
$result = $db->fetchAll(
$query,
array(
new PQO(':parent', $parent)
)
);
return $result;
}
private function getCountries() {
$db = patentionConnect();
$query =
"SELECT `fieldtitle` FROM `jos_adsmanager_field_values`
WHERE fieldid = :id";
$result = $db->fetchAll(
$query,
array(
new PQO(':id', 29)
)
);
return $result;
}
private function printCountries(array $countries) {
foreach($countries as $row) {
?>
<option value=<?=$row['fieldtitle'];?> >
<?=$row['fieldtitle'];?>
</option>
<?php
}
}
private function printCategories(array $categories) {
foreach($categories as $key => $row){
?>
<option value=<?=$row['id'];?>>
<?=$row['name'];?>
</option>
<?php
}
}
}
And the include call (which exists in the same file):
$template = new EditForm(
new AdData(),
new PhotoData(),
new UrlData($Itemid),
array(
'form.php',
'form.process.php'
)
);
$template->includeFiles();
And the main file which is included...
if ($this->formName == "pageOne") {
$this->adData->addData('category', $_POST['category']);
$this->adData->addData('subcategory', $_POST['subcategory']);
} else if ($this->formName == "pageTwo") {
$this->adData->addData('ad_Website', $_POST['ad_Website']);
$this->adData->addData('ad_Patent', $_POST['ad_Patent']);
$this->adData->addData('ad_Address', $_POST['ad_Address']);
$this->adData->addData('email', $_POST['email']);
$this->adData->addData('hide_email', $_POST['hide_email']);
$this->adData->addData('ad_phone', $_POST['ad_phone']);
$this->adData->addData('ad_Protection', $_POST['ad_Protection']);
$this->adData->addData('ad_Number', $_POST['ad_Number']);
$this->adData->addData('ad_Country', $_POST['ad_Country']);
$this->adData->addData('ad_issuedate', $_POST['issuedate'] . '/' . $_POST['issuemonth'] . '/' . $_POST['issueyear']);
} else if ($this->formName == "pageThree") {
$this->adData->addData('name', $_POST['name']);
$this->adData->addData('ad_Background', $_POST['ad_Background']);
$this->adData->addData('ad_opeartion', $_POST['ad_operation']);
$this->adData->addData('ad_advlimit', $_POST['ad_advlimit']);
$this->adData->addData('ad_status', $_POST['ad_status']);
$this->adData->addData('ad_addinfo', $_POST['ad_addinfo']);
$this->adData->addData('ad_description', $_POST['ad_description']);
$this->adData->addData('tags', $_POST['tags']);
$this->adData->addData('videolink', $_POST['videolink']);
} else if ($this->formName == "pageFour") {
foreach($_POST['jos_photos'] as $photo) {
$this->photoData->addData(
array(
'title' => $photo['title'],
'url' => $photo['url'],
'ad_id' => $this->photoData->__get('ad_id'),
'userid' => $this->photoData->__get('userid')
)
);
}
}
Update
Strange: while the error itself hadn't been quite related to what the problem was, I found that it was simply an undefined field which I hadn't implemented.
Consider this thread solved. To those who replied, I certainly appreciate it regardless.
This should work. Are you sure you're doing the include from a non-static method that's part of the class (class A in your example)? Can you post the exact code you're using?
Edit: As general advice for problems like this, see if you can trim down the code so the problem is reproducible in a short, simple example that anyone could easily copy/paste to reproduce the exact error. The majority of the time, you'll figure out the answer yourself in the process of trying to simplify. And if you don't, it will make it much easier for others to help you debug.