I am receiving an php error errors: [1]
0: {
message: "Undefined offset: 1 (Error Number: 8), (File: /Users/akashpatel/Documents/iOS development/RideShare/RideShareAPI/src/frapi/library/Frapi/Controller/Api.php at line 299)"
name: "PHP Notice error"
at: ""
}.
Below is the code.
if (isset($_SERVER['HTTP_LOGIN']))
{
list($userId, $apiKey) = explode(':', base64_decode($_SERVER['HTTP_LOGIN']));
$this->setUserId($userId);
$this->setApiKey($apiKey);
//check against DB
$sql = "SELECT * from user WHERE id=:userId AND apiKey=:apiKey";
$stmt = $db->prepare($sql);
$stmt->bindParam(':userId', $this->getUserId());
$stmt->bindParam(':apiKey', $this->getApiKey());
try
{
$stmt->execute();
$user = $stmt->fetchObject();
}
catch(PDOException $err)
{
echo $err->getMessage();
}
if ($user == null)
throw new Frapi_Error('STATUS_FORBIDDEN');
}
else
{
$this->userName = false;
$this->apiKey = false;
throw new Frapi_Error(
Frapi_Error::ERROR_INVALID_ACTION_REQUEST_NAME,
Frapi_Error::ERROR_INVALID_ACTION_REQUEST_MSG,
Frapi_Error::ERROR_INVALID_ACTION_REQUEST_NO,
Frapi_Error::ERROR_INVALID_ACTION_REQUEST_HTTP_MSG
);
}
Thanks in advance.
EDIT :
Sorry everyone. I passed incorrect values. Now I use correct one, but getting error ERROR_INVALID_ACTION_REQUEST. May be this is because it goes to else. But not getting what can be the reason. I edited the code.
This means the string did not explode into two parts and the resulting array does not have an offset 1. You should not list()-assign variables unless you are 2000% sure you have that many indexes in the array you're assigning. In this case it's out of your control, so you better check first.
Related
I have a PHP platform where user write mongodb query like picture below
and following code print result as a table
$m = new MongoClient();
$db = $m->Forensic;
$coll= $db->mobile_data;
if (isset($_POST['txt_area']) && !empty($_POST['txt_area'])) {
$d = ($_POST['txt_area']);
$p = json_decode($d);
$user_code = $coll->find($p);
When I type correct code system able to ouput all my result but if I write query wrong I am getting error message like
Warning: MongoCollection::find(): expects parameter 1 to be an array or object, null given in C:\xampp\htdocs\reports5.php on line 126
to catch that error i have tried following try catch code but no luck
try {
if (isset($_POST['txt_area']) && !empty($_POST['txt_area'])) {
$d = ($_POST['txt_area']);
$p = json_decode($d);
$user_code = $coll->find($p);
$NumberOfRow2 = $user_code->count();
$user_code->sort(array('Chat_group' => -1, 'Instant_Message' => 1 ));
}
}
catch (MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
catch (MongoException $e)
{
echo $e->getMessage();
}
catch(MongoResultException $e) {
echo $e->getMessage(), "\n";
$res = $e->getDocument();
var_dump($res);
}
what would be the best way to catch above error
The warning you're seeing is PHP complaining that $coll->find($p); expects $p to be either array or object while it's null. Quoting json_decode documentation:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
So a proper way to defend against warning would be:
$p = json_decode($d);
if ($p === null) {
echo "Provided query is invalid!";
} else {
// do your logic
}
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"] : "";
I am trying to add a product to my shopping cart.
I am getting an error saying:
Warning: Invalid argument supplied for foreach() in
It is telling me I am getting an error for the following code:
function isInCart($id) {
if (!empty($_SESSION['sess_uid']['cart'])) {
foreach ($_SESSION['sess_uid']['cart'] as $report) {
if ($report['reportID'] == $id) {
// Report ID found in Cart
return true;
}
}
// Looped through cart, ID not found
return false;
} else {
// Cart empty
return false;
}
}
The particular line from the above that is flagging the error is:
foreach ($_SESSION['sess_uid']['cart'] as $report) {
I am also getting the following error message:
Fatal error: Only variables can be passed by reference in
The code this relates to is the following:
function addToCart($id) {
$report = getReportByID($id);
$author = $report['userID'];
if (!empty($report)) {
// Got the report
if (!empty($_SESSION['sess_uid']['cart'])) {
if (!isInCart($id) && !isOwner($author) && !hasPurchased($id)) {
array_push($_SESSION['sess_uid']['cart'], $report);
return true;
} else {
return false;
}
} else {
$_SESSION['sess_uid']['cart'] = array();
if (!isInCart($id) && !isOwner($author) && !hasPurchased($id)) {
array_push($_SESSION['sess_uid']['cart'], $report);
return true;
} else {
return false;
}
}
} else {
// Unable to get report by ID
return false;
}
}
The particular line of code from the above that is flagging the error is:
array_push($_SESSION['sess_uid']['cart'], $report);
The code below is what gets my reports to populate the store
<?php
function getReportByID($id) {
$conn = new mysqli(localhost, root, DBPASS, DBNAME);
$sql = "SELECT * FROM reports WHERE reportID = '" . $conn->real_escape_string($id)."';";
// Performs the $sql query on the server
$report = $conn->query($sql);
return $report->fetch_array(MYSQLI_ASSOC);
}
?>
Any help would be greatly appreciated.
Thanks
i think this wil help:
it typcast your session as an array so even when the session is empty you dont get an error
foreach ((array)$_SESSION['sess_uid']['cart'] as $report) {
let me know if this fix the error?
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.
i have been working on some application which involves the cURL operation and then Scraping the content of particular URLs.
And there are few computation/calculations following the Scraping.
The issue which i'm facing right now is related to UNDEFINED ARRAY INDEX.
Here are few functions facing like issues:
{Notice: Undefined offset: 0 in D:\xampp\htdocs\Alps-Phase2\alps\include\alpsOP\scrap-process-request2.php on line 263}
there are more functions similar to these:
function getDomainName($objScrap)
{
try
{
$result = $objScrap->getDomainName();
return $result; //Notice: Undefined offset: 0
}
catch( Exception $e)
{
echo "Error in getDomainName !";
return FALSE;
}
}
function getDataForDomainName($objScrap)
{
try
{
$result = $objScrap->checkForKeywordInDomain();
return $result[0]; // Notice: Undefined offset: 0
}
catch( Exception $e)
{
echo "Error in getDataForDomainName !";
return FALSE;
}
}
function getDensityForDomainName($objScrap){
try
{
$result = $objScrap->getDomainDensity();
return $result[0]; // Notice: Undefined offset: 0
}
catch( Exception $e)
{
echo "Error in getDensityForDomainName !";
return FALSE;
}
}
The function definitions for some calls:
function getDomainDensity()
{
$result=$this->getDomainName();
return $this->getKeywordDensity($result);
}
function getDomainName()
{
preg_match($this->_regExpDomain,$this->_url,$match);
if($match != NULL)
return $match[2];
else
return array(
0=> 'Please check URL '.$this->$_url.' [Domain Name]',
'error' => 'Please check URL '.$this->$_url.' [Domain Name]'
);
}
function getKeywordDensity(&$subject)
{
$splitKeywordCountTotal_len=0;
$splitKeywordCount = array();
$resultArray = array();
for($count_i=0;$count_i<count($this->_keywords);$count_i++)
{
$splitKeyword = $this->splitKeyword($this->_keywords[$count_i]);
$splitKeywordCount=0;
$splitKeywordCount = $this->prepareResultArray($subject,NULL,$splitKeyword);
$matchedKeywordCharacterCount=0;
$f=0;
foreach ($splitKeywordCount as $val=>$key)
{
$splitKeywordCount[$f][2]=strlen($key[0]);
$splitKeywordCount[$f][3]=$key[1]*strlen($key[0]);
$matchedKeywordCharacterCount=$matchedKeywordCharacterCount+$splitKeywordCount[$f][3];
$f++;
}
$totalWordsInVisibleContent = $this->getNumberOfWordsInSubject($subject);
$f=0;
$totalWordsInVisibleContent_len=0;
foreach ($totalWordsInVisibleContent as $val=>$key)
{
$totalWordsInVisibleContent_len=$totalWordsInVisibleContent_len+strlen($key);
}
$splitKeywordCountTotal = 0;
for($count_j=0;$count_j < count($splitKeywordCount);$count_j++)
{
$splitKeywordCountTotal = $splitKeywordCountTotal + $splitKeywordCount[$count_j][1];
$splitKeywordCountTotal_len = $splitKeywordCountTotal_len + $splitKeywordCount[$count_j][2];
}
$resultArray[$count_i] = array();
$resultArray[$count_i][0] = $this->_keywords[$count_i];
$resultArray[$count_i][1] = $matchedKeywordCharacterCount/ ($totalWordsInVisibleContent_len);
$resultArray[$count_i][2] = $splitKeywordCountTotal;
$resultArray[$count_i][3] = $matchedKeywordCharacterCount;
$resultArray[$count_i][4] = $totalWordsInVisibleContent;
$resultArray[$count_i][5] = $splitKeywordCountTotal_len;
$resultArray[$count_i][6] = $totalWordsInVisibleContent_len;
}
return $resultArray;
}
moreover, i plan to run half a million URLs for the same application. If these NOTICES keep on showing up, my application would be facing poor performance.
So guys, need help in resolving the issue.
** sorry for the drafting of code... new to the forum , dint know how to use the constructs.. :(
Turn Off Html errors
include the following on the top
error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('html_errors', 'Off');
I have faced such an issue just today! I use PHP7.3.5 and I get the same error, for searching around I found the solution to be:
Instead of:
try
{
$result = $objScrap->checkForKeywordInDomain();
return $result[0]; // Notice: Undefined offset: 0
}
Change to:
try
{
$result = $objScrap->checkForKeywordInDomain();
if(isset($result[0])){
return $result[0];
}
}
hope this can help anyone }else{ :).