Notice: Undefined offset: 0 - php

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{ :).

Related

PHP MongoDB exception (Error handling)

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
}

PHP Shopping Cart

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?

return and echo my array from a function

I have a function that returns either a value into a variable if it is successful or it returns an errors array. see part of it below.
function uploadEmploymentDoc($var, $var2){
$ERROR = array();
if(empty($_FILES['file']['tmp_name'])){
$ERROR[] = "You must upload a file!";
}
//find the extensions
$doctypeq = mysql_query("SELECT * FROM `DocType` WHERE `DocMimeType` = '$fileType'");
$doctype = mysql_fetch_array($doctypeq);
$docnum = mysql_num_rows($doctypeq);
if($docnum == 0){
$ERROR[] = "Unsupported file type";
}
if(empty($ERROR)){
// run my code
return $var;
} else{
return $ERROR;
}
then when I run my code
$result = uploadEmploymentDoc(1, 2);
if($result !=array()){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Now my question is this. Why is my function running my code and not showing me an error when I upload an unsupported document type. Am I defining my foreach loop correctly? For some reason I cant get my errors back.
you should write like this-
if(is_array($result)){
foreach($result as $er){
echo $er."<br>";
}
} else {
//your code for handling error
}
You can get more info :http://us2.php.net/is_array
Try use
$result = uploadEmploymentDoc(1, 2);
if(!is_array($result)){
// run code
} else {
foreach($result as $er){
echo $er."<br>";
}
}
Probably will be better add parameter by reference to function for the errors array. From function return "false" if error and value if no error occurred.

errors: [1] 0: {message: "Undefined offset: 1}

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.

How to catch this error: "Notice: Undefined offset: 0"

I want to catch this error:
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (\Exception $e) {
echo "jsdlkjflsjfkjl";
}
Edit: in fact, I got this error on the following line:
$parse = $xml->children[0]->children[0]->toArray();
You need to define your custom error handler like:
<?php
set_error_handler('exceptions_error_handler');
function exceptions_error_handler($severity, $message, $filename, $lineno) {
if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (Exception $e) {
echo "jsdlkjflsjfkjl";
}
You can't with a try/catch block, as this is an error, not an exception.
Always tries offsets before using them:
if( isset( $a[ 0 ] ) { $b = $a[ 0 ]; }
I know it's 2016 but in case someone gets to this post.
You could use the array_key_exists($index, $array) method in order to avoid the exception to happen.
$index = 99999;
$array = [1,2,3,4,5,6];
if(!array_key_exists($index, $array))
{
//Throw myCustomException;
}
$a[1] = 'jfksjfks';
try {
$offset = 0;
if(isset($a[$offset]))
$b = $a[$offset];
else
throw new Exception("Notice: Undefined offset: ".$offset);
} catch (Exception $e) {
echo $e->getMessage();
}
Or, without the inefficiency of creating a very temporary exception:
$a[1] = 'jfksjfks';
$offset = 0;
if(isset($a[$offset]))
$b = $a[$offset];
else
echo "Notice: Undefined offset: ".$offset;
Important: Prefer not using this method, use others. While it works, it is ugly and has its own pitfalls, like falling into the trap of converting real and meaningful output into exceptions.
Normally, you can't catch notices with a simple try-catch block. But there's a hacky and ugly way to do it:
function convert_notice_to_exception($output)
{
if (($noticeStartPoint = \strpos($output, "<b>Notice</b>:")) !== false) {
$position = $noticeStartPoint;
for ($i = 0; $i < 3; $i++)
$position = strpos($output, "</b>", $position) + 1;
$noticeEndPoint = $position;
$noticeLength = $noticeEndPoint + 3 - $noticeStartPoint;
$noticeMessage = \substr($output, $noticeStartPoint, $noticeLength);
throw new \Exception($noticeMessage);
} else
echo $output;
}
try {
ob_start();
// Codes here
$codeOutput = ob_get_clean();
convert_notice_to_exception($codeOutput);
} catch (\Exception $exception) {
}
Also, you can use this function for to catch warnings. Just change function name to convert_warning_to_exception and change "<b>Notice</b>:" to "<b>Warning</b>:".
Note: The function will catch normal output that contains:
<b>Notice</b>:
To escape from this problem, simply, change it to:
<b>Notice:</b>
For the people who are getting the error
PHP Notice: unserialize(): Error at offset 191 of 285 bytes in ...
and are getting the data from a database, Make sure that you have the database set the the correct encoding, I had the database set as latin1_swedish_ci and all of the data looked perfect, Infact when i copied it into a online unserialize it worked fine. I changed the collation to utf8mb4_unicode_ci and all worked fine.
Source User Contributed Notes: https://www.php.net/manual/pt_BR/function.unserialize.php
I tried to utf8_decode before unserialize, and it's works fine.
Im sure why the Error Throw but i fix some..
in html2pdf.class.php
on Lines 2132:
//FIX:
$ctop=$corr[$y][$x][2]<=count($sw)?$corr[$y][$x][2]:count($sw);
$s = 0; for ($i=0; $i<$ctop; $i++) {$s+= array_key_exists($x+$i, $sw)? $sw[$x+$i]:0;}
SAME On line 2138:
//FIX:
$ctop=$corr[$y][$x][2]<=count($sw)?$corr[$y][$x][2]:count($sw);
for ($i=0; $i<$ctop; $i++) {
the problem the array $sw not have a key of $corr[$y][$x][2] so i fix the loop for to max count($sw) to fix ..
I dont know if that create an another consecuense but i resolve my problem y dont have any more errors..
So i hope works to you ..!!!
Beats Reguards

Categories