PHP Fatal Error Cannot Use String Offset As Array - php

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"] : "";

Related

Header may not contain more than a single header, new line detected error [duplicate]

This question already has answers here:
getting warning "Header may not contain more than a single header, new line detected"
(9 answers)
Closed 9 months ago.
I managed to get every other error ironed out, but I am stuck with this error! For the life of me, I cannot seem to diagnose where I went wrong. Any help from you brilliant people out there would be amazing!
I made a form editing php where it is supposed to edit a submission made into the system. This is then processed by my processing php but for some reason I am getting a "header may not contain more than a single header" error in my form submission. I changed the header code multiple times but I do not know why I am still getting it: https://imgur.com/reX4Yyb
Edit:
Also wanted to add that this code was working fine for about a month. The only thing I changed was updating the hosting service platform from PHP 7.3 -> PHP 7.4. I tried reverting and it exactly the same error.
if($_POST['form_submitted'] == 'editgroupreferral'){
include("../../inc/inc.con.php");
/* assign values to checkboxes */
if(isset($_POST['OtherServices'])){
$otherservices = 1;
} else {
$otherservices = 0;
}
if(isset($_POST['Medication'])){
$medication = 1;
} else {
$medication = 0;
}
if(isset($_POST['HaveAllergies'])){
$allergies = 1;
} else {
$allergies = 0;
}
if(isset($_POST['Device'])){
$device = 1;
} else {
$device = 0;
}
if(isset($_POST['Share'])){
$share = 1;
} else {
$share = 0;
}
if(isset($_POST['TakeTurns'])){
$taketurns = 1;
} else {
$taketurns = 0;
}
if(isset($_POST['Wait'])){
$wait = 1;
} else {
$wait = 0;
}
if(isset($_POST['MultInstructions'])){
$multinstr = 1;
} else {
$multinstr = 0;
}
if(isset($_POST['SitChair'])){
$sitchair = 1;
} else {
$sitchair = 0;
}
if(isset($_POST['Routine'])){
$routine = 1;
} else {
$routine = 0;
}
/* insert vars from form into ReferralSC table */
$sql = "UPDATE ReferralGR SET
ReferrerName = :refname,
ReferrerRelationship = :refrelationship,
ReferrerPhone = :refphone,
ReferrerEmail = :refemail,
ReferMethod = :refmethod,
RefSupport = :refsupp,
OtherServices = :otherservices,
School = :school,
Diagnosis = :diagnosis,
Medication = :medication,
MedicationList = :medicationlist,
HaveAllergies = :allergies,
AllergiesList = :allergieslist,
Device = :device,
Share = :share,
TakeTurns = :taketurns,
Wait = :wait,
MultInstructions = :multinstr,
SitChair = :sitchair,
Routine = :routine,
ExplainFurther = :explain,
HeardAbout = :heardabout,
RefNotes = :notes
WHERE ref_id = :grid";
$s = $pdo->prepare($sql);
$s->bindvalue(':refname', $_POST['ReferrerName']);
$s->bindvalue(':refrelationship', $_POST['ReferrerRelationship']);
$s->bindvalue(':refphone', $_POST['ReferrerPhone']);
$s->bindvalue(':refemail', $_POST['ReferrerEmail']);
$s->bindvalue(':refmethod', $_POST['ReferMethod']);
$s->bindvalue(':refsupp', $_POST['RefSupport']);
$s->bindvalue(':otherservices', $otherservices);
$s->bindvalue(':school', $_POST['School']);
$s->bindvalue(':diagnosis', $_POST['Diagnosis']);
$s->bindvalue(':medication', $medication);
$s->bindvalue(':medicationlist', $_POST['MedicationList']);
$s->bindvalue(':allergies', $allergies);
$s->bindvalue(':allergieslist', $_POST['AllergiesList']);
$s->bindvalue(':device', $device);
$s->bindvalue(':share', $share);
$s->bindvalue(':taketurns', $taketurns);
$s->bindvalue(':wait', $wait);
$s->bindvalue(':multinstr', $multinstr);
$s->bindvalue(':sitchair', $sitchair);
$s->bindvalue(':routine', $routine);
$s->bindvalue(':explain', $_POST['ExplainFurther']);
$s->bindvalue(':heardabout', $_POST['HeardAbout']);
$s->bindvalue(':notes', $_POST['RefNotes']);
$s->bindvalue(':grid', $_POST['ref_id']);
$s->execute();
header('location:../refer_gr/referral-view.php?rid=' . $_POST['ref_id'] );
}
This warning occurs to indicate that you might have a new line [/n] in the string content of your variables. The solution is to strip out the passable new line contents of the variable Like this
$val=$_POST['ref_id'];
$url="../refer_gr/referral-view.php?rid='$val'";
$url=str_replace(PHP_EOL, '', $url);
header("Location: $url");
Okay, this one was a toughie but I figured it out. Here is my method:
So the clue lies in the error itself. It was pointing me from my processing php. But it was only because the data being asked in the header (requires a reference ID) is wrong.
The problem was in the reference ID (after much debugging). It was taking the wrong value from the wrong variable. This was in the php form page not the php processing page.
So here is the solution:
$s->bindvalue(':refid', $refid);
Rest of the code:
<input type="hidden" name="ref_id" value="<?php echo $rid; ?>" >
The variable $rid is not the same as the variable $refid.
Here is the fix:
<input type="hidden" name="ref_id" value="<?php echo $refid; ?>" >
This means that with this type of error, it might be worth looking at which part of the code it is trying to get the value from and start debugging from there.
Thanks for the help everyone!

Php 7 "cannot use string offset as an array"

We've recently upgraded to Php 7.4 and are encountering a potential fatal error alert for the following code block:
$total = 0;
$balance = 0;
if (is_array($company['history']) && ($histCount = count($company['history']))) {
for ($i = $histCount - 1; $i >= 0; $i--) {
$total += $company['history'][$i]['amt_total'];
$balance += $company['history'][$i]['due'];
$company['history'][ $i ]['balance'] = $balance; // EA flags as potential fatal error
$company['history'][ $i ]['total'] = $total; // EA flags as potential fatal error
}
}
Each history element in the $company has (among others) amt_total, due, balance, and total initialized, with the last two being initialized to 0.
EA flags the two lines indicated, saying "Could provoke a PHP Fatal error (cannot use string offset as an array)."
Grateful to anyone who can help me understand what's wrong here.
ADDITIONAL INFO
Someone asked where the code for defining $company comes from...
foreach ($this->orderList as $order) {
if ($order['amt_paid'] !== $order['real_amt_paid'] && !empty($order['real_amt_paid'])) {
$order['amt_paid'] = $order['real_amt_paid'];
}
$row = [];
foreach ($this->customerHistoryColumns as $col) {
$order[$col[0]] = ($order[$col[0]] === null ? "" : str_replace("&", "&", $order[$col[0]]));
switch ($col[0]) {
...
case "due":
$row['due'] = $order['amt_total'] - $order['amt_paid'];
break;
...
default:
$row[$col[0]] = $order[$col[0]];
break;
}
}
$row['balance'] = 0;
$row['total'] = 0;
$arr['history'][] = $row;
}
return $arr['history'];
The company itself is defined elsewhere; this is simply retrieving the history element.
FWIW, the code has worked flawlessly for years; it's the upgrade to Php7 that has raised this issue.

PHP Foreach with mysql_fetch_array server status

Im trying to create a cronjob script, which checks the status of a few servers.
Somehow it only uses the first ip in my table.
$aQ = db::aQuery("SELECT hostIp FROM `gh_server_hosts`");
$a = mysql_fetch_array($aQ);
foreach ($a as $value) {
$timeout = "10";
$ssh= #fsockopen("$value","22",$timeout);
if($ssh) {
$status = 1;
}
else {
$status = 0;
}
$time = time();
if(db::aQuery("UPDATE `gh_server_hosts` SET hostLastScanned='".$time."', hostLastStatus='".$status."' WHERE hostIp = '".$value."'")) {
echo "scanned";
} else {
echo "error";
}
}
You have to put mysql_fetch_array in loop to get all records like this:
$aQ = db::aQuery("SELECT hostIp FROM `gh_server_hosts`");
while ($value = mysql_fetch_assoc($aQ)) {
$timeout = "10";
$ssh= #fsockopen($value['hostIp'],"22",$timeout);
// Rest of your code
}
I have used mysql_fetch_assoc instead of mysql_fetch_array to limit the output array. Also, as mentioned by others mysql_* functions are deprecated so kindly update your code before running this code on PHP 5.5+...
mysql_fetch_assoc() will work instead of mysql_fetch_array() but do note about the deprecation warning with mysql. (Aside from the security concerns, your code will fail if PHP is upgraded to 7.0).

PHP Fatal error: Call to a member function asXML() on a non-object for Google Calendar XML

I need some help with this code. It was running perfectly up until a couple of weeks ago.
<?php
date_default_timezone_set('America/New_York');
$cache_time = 3600*12;
$feedRegular = "https://www.google.com/calendar/feeds/invernesscalvary.com_fipcro22aiul8uaa2hg80h6gmc%40group.calendar.google.com/public/basic?orderby=starttime&singleevents=true&futureevents=true&max-results=999&sortorder=a";
$feedFeature = "https://www.google.com/calendar/feeds/invernesscalvary.com_8ohrv5fhqf7o2r9jhgsr2q2764%40group.calendar.google.com/public/basic?orderby=starttime&singleevents=true&futureevents=true&max-results=3&sortorder=a";
$cache_file_reg = $_SERVER['DOCUMENT_ROOT'].'/cache/gcal.xml';
$timedif_reg = #(time() - filemtime($cache_file_reg));
$xmlRegular = "";
if (file_exists($cache_file_reg) && $timedif_reg < $cache_time) {
$str_reg = file_get_contents($cache_file_reg);
$xmlRegular = simplexml_load_string($str_reg);
} else {
$xmlRegular = simplexml_load_file($feedRegular);
if ($f_reg = fopen($cache_file_reg, 'w')) {
$str_reg = $xmlRegular->asXML();
fwrite ($f_reg, $str_reg, strlen($str_reg));
fclose($f_reg);
} else { echo "<p>Can't write to the cache.</p>"; }
}
$xmlRegular->asXML();
$cache_file_fea = $_SERVER['DOCUMENT_ROOT'].'/cache/gcal_featured.xml';
$timedif_fea = #(time() - filemtime($cache_file_fea));
$xmlFeature = "";
if (file_exists($cache_file_fea) && $timedif_fea < $cache_time) {
$str_fea = file_get_contents($cache_file_fea);
$xmlFeature = simplexml_load_string($str_fea);
} else {
$xmlFeature = simplexml_load_file($feedFeature);
if ($f_fea = fopen($cache_file_fea, 'w')) {
$str_fea = $xmlFeature->asXML();
fwrite ($f_fea, $str_fea, strlen($str_fea));
fclose($f_fea);
} else { echo "<p>Can't write to the cache.</p>"; }
}
if (is_object($xmlFeature)) {
$xmlFeature->asXML();
}
$n = 0;
foreach ($xmlRegular->entry as $entry) {
$n++;
$ns_gd = $entry->children('http://schemas.google.com/g/2005');
$eDate = date("M", strtotime($ns_gd->when->attributes()->startTime));
$eDay = date("j", strtotime($ns_gd->when->attributes()->startTime));
$eTime = date("g:ia", strtotime($ns_gd->when->attributes()->startTime));
$eLink = date("Y/m", strtotime($ns_gd->when->attributes()->startTime));
$title = str_replace(" & ", " & ", $entry->title);
$where = $ns_gd->where->attributes()->valueString;
$link = $entry->link->attributes()->href;
echo "<li>\n";
echo "<span class=\"eDate\">$eDate <span class=\"eDay\">$eDay</span> # $eTime</span><a rel=\"$eLink\" title=\"# $where\" href=\"#\">";
echo "<p class=\"eTitle\">$title</p></a>\n";
echo "</li>\n\n";
if($n == 3) break;
}
?>
FIXED Fatal error: Call to a member function asXML() on a non-object in /home/calvary/public_html/index.php on line 83
FIXED If I do a var_dump($xmlRegular) after the simplexml_load_string($str_reg) I get a boolean false.
UPDATE Warning: main() [function.main]: Node no longer exists in /home/calvary/public_html/index.php.new on line 132 now shows up twice for each line 132, 133, 134, 136, and 139 which are the lines starting with $eDate $eDay $eTime $eLink and $where.
You're getting this error because the $xmlRegular variable is not an object. Likely, it's a Boolean with a false value. This is because the simplexml_load_string or simplexml_load_file is failing to return an object. I believe the most probable reason would be simplexml_load_file does not have read permissions or cannot find the file.
I'd recommend var_dump'ing a value and then running an 'exit;' to see what the value at that point is. This way you can see which value is incorrect.
Please let us know if you make any progress on this and I'd be happy to provide more input!
EDIT: Going directly to the URL you are using ($feedRegular) I get a Forbidden 403 error. This would cause your $xmlRegular to be false instead of an object.

json_decode warning: Creating default object from empty value

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.

Categories