EDUSOHO踩坑笔记之五十三:Undefined offset故障排除
今天在跟踪EDUSOHO的程序时,发现下面的错误,导致服务器的数据库访问负荷飙高,以为是收到攻击了,后来排查下来发现不是,是因为一个访问边界没控制住,数组越界导致提取数据失败,不断重试导致的数据库访问飙高,像被攻击了一样。
[06-Nov-2020 09:04:03 Asia/Shanghai] PHP Notice: Undefined offset: -1314340 in /mydata/wwwroot/edusoho/plugins/JsonRpcApiPlugin/Biz/JsonRpcApi/Service/Impl/JsonRpcApiServiceImpl.php on line 252
[06-Nov-2020 09:04:03 Asia/Shanghai] PHP Notice: Undefined offset: -1302009 in /mydata/wwwroot/edusoho/plugins/JsonRpcApiPlugin/Biz/JsonRpcApi/Service/Impl/JsonRpcApiServiceImpl.php on line 252
[06-Nov-2020 09:04:03 Asia/Shanghai] PHP Notice: Undefined offset: -1338698 in /mydata/wwwroot/edusoho/plugins/JsonRpcApiPlugin/Biz/JsonRpcApi/Service/Impl/JsonRpcApiServiceImpl.php on line 252
[06-Nov-2020 09:04:03 Asia/Shanghai] PHP Notice: Undefined offset: -1322886 in /mydata/wwwroot/edusoho/plugins/JsonRpcApiPlugin/Biz/JsonRpcApi/Service/Impl/JsonRpcApiServiceImpl.php on line 252
[06-Nov-2020 09:04:03 Asia/Shanghai] PHP Notice: Undefined offset: -1322887 in /mydata/wwwroot/edusoho/plugins/JsonRpcApiPlugin/Biz/JsonRpcApi/Service/Impl/JsonRpcApiServiceImpl.php on line 252
[06-Nov-2020 09:04:03 Asia/Shanghai] PHP Notice: Undefined offset: -1302010 in /mydata/wwwroot/edusoho/plugins/JsonRpcApiPlugin/Biz/JsonRpcApi/Service/Impl/JsonRpcApiServiceImpl.php on line 252
排查下来的原因,在循环之前没有做list数据大小判断,并且第一个循环还是count()-1,如果为零时,又减一,导致负数组,就报此类错误
public function getNextVideoTaskIdByTaskResultList($taskResultList)
{
if (count($taskResultList)>=1){ //前面加上列表记录必须至少有一个数据
for ($i=(count($taskResultList)-1);$i<=count($taskResultList);$i--) {
$task = $this->getTaskDao()->get($taskResultList[$i]['courseTaskId']);
if (empty($task))
continue;
return $task['id'];
}
} //判断尾
}
这问题很常出现在数组中的,程序是能正确地运行下去,但是在日志中这样的报警:Notice: Undefined offset: ….. 如上面的代码示例,常规的做法,是把数组大小做个判断,这样就能正常处理数据了,不再报错了.
问题是解决后offset:接下去的数字是出错的数组下标,一般是超出了数组的取值范围,如定义了数组$A[]有10个元数,如果出现了$A[10]就会出现错误(Notice: Undefined offset: 10 ….),因为数组的下标是从0开始的,所以这个数组的下标就只能是0~9.因此在出现这类问题时,不要急于用抑制显示的方法一定要注意你所用的数组下标,仔细思考一下,问题一定会很快得到解决的 !发也有可能是unset数组后再尝试读取其内容。
如有的网友写的下面的代码:
<?php# ...function get_match($regex, $content) {
preg_match($regex,$content,$matches);
return $matches[1]; // ERROR HAPPENS HERE}
原因preg_match
没找到匹配,$matches
则为空数组。因此,正确的写法preg_match
在访问之前检查是否找到匹配项$matches[0]
,如下:
function get_match($regex,$content){
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}}