json_decode warning: Creating default object from empty value - php

I get this error and is affecting my modules from working properly. I am not sure how to fix it. Most of the help sites said that they got the error after they upgraded but since I did not upgrade I am not sure why I got this error.
Error Message: Warning: Creating default object from empty value in
..../aac/administrator/components/com_poweradmin/helpers/history.php on line 125.
The below starts from line 116 to 154.
Line 125: "$listPage->params = (isset($listPage->params)) ? str_replace('&', '&', $listPage->params) : '';"
Codes used:
private static function updateHistoryState($post)
{
if (!isset($_COOKIE['jsn-poweradmin-list-page']))
return;
$listPage = json_decode($_COOKIE['jsn-poweradmin-list-page']);
if ($listPage == NULL)
$listPage = json_decode(stripslashes($_COOKIE['jsn-poweradmin-list-page']));
$listPage->params = (isset($listPage->params)) ? str_replace('&', '&', $listPage->params) : '';
$id = array();
if (isset($post['id']) && is_numeric($post['id']))
$id[] = $post['id'];
else if (isset($post['id']) && is_array($post['id']))
$id = array_merge($id, $post['id']);
if (isset($post['cid']) && is_numeric($post['cid']))
$id[] = $post['cid'];
else if (isset($post['cid']) && is_array($post['cid']))
$id = array_merge($id, $post['cid']);
$isDelete = (int)preg_match('/\.?(delete|remove|trash)$/i', $post['task']);
if (count ($id) && (is_numeric($id) || is_array($id))) {
// Bypass if any of id list is not a number
if (is_array($id)) {
foreach ($id as $i) {
if (!is_numeric($i)) {
return;
}
}
}
$dbo = JFactory::getDBO();
$dbo->setQuery("UPDATE #__jsn_poweradmin_history SET is_deleted={$isDelete} WHERE list_page_params LIKE '{$listPage->params}' AND object_id IN (".implode(',', $id).")");
#$dbo->query();
}
}

This is not really an error but a warning.
It appears that JSON you are trying to decode is malformed and that json_decode does not manage to return you an object of type stdClass. Probably json_decode returns NULL.
Basically the warning is about trying to assign a property to a variable has not been initialized as a stdClass object.

Related

PHP Fatal Error Cannot Use String Offset As Array

I keep getting a fatal error when a script is ran on my php server,
This web app was built ten years ago and I am currently clearing errors so we can start updating it. Current version PHP 5.2.17
Fatal error: Cannot use string offset as an array in /home/user/public_html/admin/script.php on line 1418
This is the line the error is on,
$name = $d["#"]["_Name"];
This is the full function,
if (isset($b["_BORROWER"]["EMPLOYER"])) {
if (!isset($b["_BORROWER"]["EMPLOYER"][0])) {
$temp = $b["_BORROWER"]["EMPLOYER"];
unset($b["_BORROWER"]["EMPLOYER"]);
$b["_BORROWER"]["EMPLOYER"][0] = $temp;
}
foreach($b["_BORROWER"]["EMPLOYER"] as $c => $d) {
$pid = '0';
// Finish up.
$item["type"] = "Personal";
$name = $d["#"]["_Name"];
//check for files in other bureaus
$query = doquery("SELECT name,id FROM <<myitems>> WHERE cid='".$client["id"]."' AND type='Personal'");
$results = dorow($query);
if($results){
if(isset($results['name'])){
$temp = $results;
unset($results);
$results[0] = array($temp);
}
foreach($results as $c){
if(isset($c['name'])){
if($address == decrypt_string($c['name'])) {
$pid = $c['id'];
break;
};
}
}
}
Does anyone understand what is triggering this error and how to fix it?
You can use isset() to check the array value exists or not like,
$name = isset($d["#"]["_Name"]) ? $d["#"]["_Name"] : "";

get results returned in a function

i have this inside a php function:
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
so its returning all of the values in the $result variable
when i do a print_r on the function, the results display like this:
stdClass Object
(
[domainname] => domain.com
[element] =>
[availability] => false
)
i am calling the function with this code:
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
so i tried to get the returned by doing $domain->availability but its not returning the value, example:
if($domain->availability) {
echo 'yes';
} else {
echo 'no';
}
am i trying to get the data the incorrect way?
UPDATE
the full function is:
if(!function_exists("domainNameCheck")) {
function domainNameCheck($domainName, $element) {
$result = '';
$client = new IcukApiClient();
$client->username = "username";
$client->key = "pass";
$client->encryption = "SHA-512";
$req = new IcukApiRequest();
$req->url = "/domain/availability/" . $domainName;
$req->method = "GET";
$res = $client->send($req);
$availability = 'unknown';
if ($res->success) {
$obj = json_decode($res->response);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
}
}
Your main problem seems to be that you are calling a function with 2 parameters but passing only one parameter
function domainNameCheck($domainName, $element) {}
// called like this (one parameter)
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
This should be generating a compile error!
Also here
if ($res->success) {
$obj = json_decode($res->response);
// check what $obj->available is set to
// it may also be a string and not a boolean
print_r($obj);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
Please note that there are two error/warning messages PHP is giving:
E_WARNING : type 2 -- Missing argument 2 for domainNameCheck()
E_NOTICE : type 8 -- Undefined variable: element
You should fix those errors, and make sure you are informed of errors during development.
Secondly, you have defined your availability as a string by assigning "false", "true", or "unknown". So when you do this:
if($domain->availability) {
... that will be true for all three values, because strings are true for PHP when converted to boolean (except when empty). To illustrate, this will echo "hello":
if ("false") echo "hello";
So you need to change your test like this:
if($domain->availability === "true") {
Or, If you want to define $domain->availability as a true boolean, then you need to alter the assignments in your function, like this:
....
$availability = $obj->available; // assuming that is a boolean!
}
else {
$availability = null; // unknown
}
... and then you can do what you had:
if($domain->availability) {
Likely because $domain->availability is boolean
To output you can first check whether its true or false and output accordingly
here's a simple example:
if ($domain->availability){
echo 'Available';
}
else {
echo 'Not Available';
}

debug_backtrace - long parameter

I have the following function:
function backtrace($Object=false)
{
$x = 0;
foreach((array)debug_backtrace($Object) as $aVal)
{
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}
But when I use it, I'm getting an error like below:
Warning: debug_backtrace() expects parameter 1 to be long, string given in /mypath/ on line 717 ---> foreach((array)debug_backtrace($Object) as $aVal)
What's causing the error? How can I fix it?
The first parameter of debug_backtrace() is a bitmask of options (i.e. a long). It is a simple boolean true/false in PHP versions prior to 5.3.6.
To fix it, either don't pass in the $Object variable you're currently passing in or update it to be any combination of the supported options that you want to be used.
Example:
$Object = DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT;
If you want to add a pre-condition to your current block of code that will set a default value if $Object is invalid, you could try something like:
function backtrace($Object = false) {
if (!is_long($Object) || (!($Object & DEBUG_BACKTRACE_PROVIDE_OBJECT) && !($Object & DEBUG_BACKTRACE_IGNORE_ARGS))) {
$Object = 0;
}
$x = 0;
foreach((array)debug_backtrace($Object) as $aVal) {
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}
for php >= 5.3.6, you should use bitmask options
function backtrace($Object=false) {
$x = 0;
foreach((array)debug_backtrace($Object ? DEBUG_BACKTRACE_PROVIDE_OBJECT : 0) as $aVal)
{
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}

Variable set to empty from JSON, not returning null

I'm calling in data from a JSON file. One of my elements is:
"mainImg_select":""
Sometimes this has a value, sometimes it won't - in this case it's empty. I put this (as well as other) variables in an object called Product.
When trying to set $product -> mainImg, I'm trying to see whether the JSON value is empty or not. If it's empty, I want to get the first value of another set of images, $more_imgsand make that the main image. Here's my code:
if(!is_null($mainImg)) {
$product->mainImage = $html->find($mainImg, 0)->src;
for ($idx = 0; $idx < 10; $idx++) {
$more = $html->find($more_imgs, $idx);
if (!is_null($more)) {
$product->moreImages[$idx] = $more->src;
} else {
return;
}
}
} else {
for ($idx = 0; $idx < 10; $idx++) {
$more = $html->find($more_imgs, $idx);
if (($idx == 0) && (!is_null($more))) {
$product->mainImage = $more->src;
} elseif (!is_null($more)) {
$product->moreImages[$idx] = $more->src;
} else {
return;
}
}
}
When I run the code, I get Notice: Trying to get property of non-object in relation to $product->mainImage = $html->find($mainImg, 0)->src;
I assume this has something to do with the if(!is_null($mainImg)) above it, because $mainImg SHOULD be null as defined in the JSON. If not, what's the best thing to use here?
EDIT: Here's some more detailed code for when the Product object is being set:
http://pastebin.com/EEUgpwgn
You should change !is_null to !empty as is_null() will return false even if "mainImg_select" is equal to empty string "".
Whether the $mainImg isn't found on your HTML; the code $html->find($mainImg, 0) will return null and then you will attempt to access the src parameter of a null object.
( from the Documentation of the php simple HTML Parser Library :
// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);
)
You have to do this:
if (null !== ($img = $html->find($mainImg, 0))) {
$imgSrc = $img->src; // Here the HTML Element exists and you can access to the src parameter
}

Undefined Index (Laravel)

I'm bashing my head against my desk trying to figure out why this PHP code is causing this error: Undefined index: arr. I'm using Laravel, and this code works like gold outside of it, but inside Laravel, it's returning the undefined index error.
Here's the code:
function set_pilots_array($line_array)
{
$airports = $this->airports;
$pilots = $this->pilots;
foreach($airports as $airport)
{
if($airport == $line_array[11] || $airport == $line_array[13])
{
if($airport == $line_array[11])
{
$deparr = "dep";
}
if($airport == $line_array[13])
{
$deparr = "arr";
}
$this->pilots[$deparr][] = array($line_array[0], $line_array[11], $line_array[13], $line_array[7], $line_array[5], $line_array[6], $line_array[8]);
}
}
}
function get_pilots_count()
{
$count = count($this->pilots['dep']) + count($this->pilots['arr']);
return $count;
}
This sort of goes with my other question: Grab and Explode Data It's pulling the data from the data file using this code:
elseif($data_record[3] == "PILOT")
{
$code_obj->set_pilots_array($data_record);
}
Which later does this:
$code_count = $code_obj->get_pilots_count();
You do not have $this->pilots['arr'] set. In other words, if you look at the output of var_dump($this->pilots);, you shall see there is no arr key-value pair. I suggest you this fix:
$count = count((isset($this->pilots['dep']) ? $this->pilots['dep'] : array())) + count((isset($this->pilots['arr']) ? $this->pilots['arr'] : array()));
Actually, this is not a fix - this is more like a hack. To make your code correct i suggest you to set the default values for those $pilots['arr'] and $pilots['dep'] values:
function set_pilots_array($line_array)
{
$airports = $this->airports;
$pilots = $this->pilots;
foreach (array('dep', 'arr') as $key)
{
if (!is_array($pilots[$key]) || empty($pilots[$key]))
{
$pilots[$key] = array();
}
}
// ...
}
Well there is too little code to really figure out what is going on, but based on what I see:
if($airport == $line_array[13])
this condition is never being met and so $deparr = "arr"; never happens and because of this
count($this->pilots['arr']);
is giving an undefined index error
You can easily suppress this by:
$count = count(#$this->pilots['dep']) + count(#$this->pilots['arr']);
your problem is that you are accessing all of your indexes directly without checking if they exist first.
assume that in laravel something is causing the array to not be populated.
in order to fix this, you should either iterate through the array with a foreach, or do a if(!empty($line_array[13])) {} before accessing it.

Categories