Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP "Notice: Undefined index" is it harmless or a real error?

Tags:

php

debugging

While my site was working without any problem I suddenly started to have a really high CPU usage on my server so I started to check the code more carefully and enabled E_ALL error reporting.

Then I found out I had a great many of this "notices":

Notice: Undefined index: userID in /var/www/vhosts/mydomain.com/httpdocs/header.php on line 8

Most or them refer to unset cookies, for example this:

$uid = $_COOKIE['userID'];

If the user is unlogged I get a notice right there, and every time I use $uid.

What I want to know if this: Are this notices harmless or can they really cause any problems in my site? (Speed issues, errors etc.)

like image 726
lisovaccaro Avatar asked Dec 13 '22 00:12

lisovaccaro


1 Answers

It is a notice only, try this code:

$uid = isset($_COOKIE['userID']) ? $_COOKIE['userID'] : 0;

It is not hamless (depending on the point of view), and you can disable this with error reporting functions, otherwise, the correct way is verify if index exists isset($_COOKIE['userID']) and if not, define a default value (null for instance)

$var = isset($foo) ? $foo : 'default';

You need to verify if variable exists, if you don't known it exists or not.

$var = 'foo'
if($var == 'foo') { // I known $var is defined, because I have defined it.
    [..]
}

/** 
 * Above, I don't known if user go to mywebsite.com/index.php or
 * mywebsite.com/index.php?foo=bar, so, I need to verify if index is defined
 */
if(isset($_GET['foo']) && $_GET['foo'] == 'bar') {
    [...]
}
like image 70
Gabriel Santos Avatar answered Feb 20 '23 06:02

Gabriel Santos