PHP Notices and Warnings - php

I have looked far and wide but haven't been able to find anything related to this specific situation, I am a backend developer and always write (something similar to):
if (!defined("something")) define("something", true);
instead of just
define("something"; true);
The second snippet will trigger a Notice if the file is included more than once. Similar situation with array indexes:
$data = array();
echo $data["does not exist"];
will trigger a notice, so my preferred way is to:
$data = array();
if (isset($data["does not exist"]) echo $data["does not exist"];
else echo "Missing info";
PHP has the ability to suppress these messages but I keep them enabled because I consider these checks good practice, but I lack the evidence to prove that they are needed and recently a coworker argued that there is no effect in coding without the checks.
Are you aware of any security implication in not writing the checks? or am I perhaps being paranoid and disabling the notices is acceptable?
PS: Not sure if this question is more suitable for StackOverflow but feel free to let me know and I'll try to move it.

Disabling notices during development is not acceptable, as it points out problems with your code. Ideally, your code should be able to run with the E_ALL, and E_STRICT error reporting levels, and still not report any errors. Exact details are dependant on the PHP version, documentation can be found here.
I do not think either option is more, or less insecure than the other, unless there is another security issue it may somehow be masking. I believe that either form is bad practice though.
When a site is in production it is important to only log errors, and set ini.display_errors off. Reducing the error reporting level in production may be useful if it is impossible to deal with code producing large amounts of certain errors, but that code should be rectified.
I do believe that code should avoid generating notices, it may be a "lesser" issue, but it is still an issue which should be taken care of at development time.
The correct way to avoid these errors is simply to avoid including files more than once. (See: include_once(), or require_once()) If you are using a framework, it likely includes a method to handle includes for you. Consult the relevant documentation, and ensure that you are using their implementation for including files.

Avoiding notices is a good practice.
Probably you should learn a little bit of defensive programming and follow The Right Way.
Hiding errors and notices during the development can cause serious problems in future.
Usually, notices tells you about bad programming style or non-obvious bugs, which tends to tricky bugs, unmaintainable code and security vulnerabilities.
Good code never produce notices and errors because it controls the situation when they can happens.

There are plenty of ways to handle errors and exceptions in system. I worked with plenty of frameworks and believe me they don't rely on display_errors and ini_config flags.
PHP has advance facility to handle errors and exception that generated by code using set_exception_handler and set_error_handler. So if you want to hide errors then you can turn off display_errors but you should put above two functions to log your errors.
Defensive programming is very useful if you want to sit back and relax after uploading work over production side.

Related

Will Index Errors Cause Security Issues?

I need to ask a simple question to make sure, being stupid and my first attempt in making this feature I forgot to add in isset() when needed now if I remove error_reporting(0); it will come up these error and I don't feel like re-writing the functionality or removing each error one by one and yes eventually I re-write it probably when I have the time.
The question is will having these errors cause any security or performance issues?
Thanks!
This will have a very minor, practically un-noticable affect on execution time, as if PHP is going to report that a variable is not set, it has to execute a little more code.
The only instance in which I think this could become a security issue is if you have error reporting enabled on a live site. In which end-users can see a snippet of code and what panguage you are using.
See: http://php.net/manual/en/function.error-reporting.php
it could cause some problems of performance if there is more than 1000 or 10000 errors notice , depending of your configuration, off course.

Should a premium PHP script run notice-free?

Personally, I always try to ensure my scripts run without any notices at all, but I consider myself to be pretty anal about that sort of thing, and with notices on in development, you can easily spot an miss-spelled variables or other minor problems.
The reason I'm asking this question is that a few premium (ie paid-for) Wordpress plugins I am using from a popular Wordpress plugin site produce a lot of notices, sometimes 10+ on a page. Is this acceptable for something I've paid for?
It's not hard to do suppress notices like this:
if(isset($_GET['var']) && $_GET['var'] == 'foo') {
These things could obviously cause more headaches down the line as a script grows.
Should a PHP script run notice-free?
Yes. The feedback is there to help improve your script and catch possible mistakes. Beyond that, it gets very subjective and I'll refrain from posting opinions.
This is perhaps a matter of opinion, but I don't think it is acceptable even in an Open Source script which can be used for free. I remember installing VirtueMart once to find the main index.php littered with E_NOTICE errors. I simply stopped them from displaying, but that's not really the ideal solution!
As you say, it isn't at all hard to suppress notices, and I believe it should always be done to prevent unexpected bugs from occurring.
I think it is totally ok for a script to generate Notices, after all they are only Notices.
They are intended for helping the developer to find bugs, but also show a lot of unnessecary information.
Your example
if(isset($_GET['var']) && $_GET['var'] == 'foo') {
would be mouch shorter if you wouldn't care about the notice:
if($_GET['var'] == 'foo') {
This leads to shorter and easier to maintain code (because you don't need to change the name twice if you cange it).
So for me Notices are a tool for finding bugs like a profiler or a debugger. You can use them (and clean your code from the unnessecary ones) or you get rid of your bugs in any other way.

php: "notice" warnings on different machine

i've set up all my php stuff on a new machine and i'm getting really lots of notices warnings.
my code is working properly without errors on my old machine.
eg. the following line (which should get a recordset value) will cause a notice:
$ID = $rs[id];
the reason is the missing quotes for the id fields, but also things like calling $_GET on a non-existing value will cause notices.
anyone knows what's the reason for this?
i'd love keeping the "simple" way of coding like on my old machine without having to hassle with quotes on recordsets or tons of isset() - any ideas?
thanks
The PHP installation in the new machine has a more robust configuration that shows notices, and not only errors. That's good. I would never write or accept in my server a PHP script that fires some notice.
This kind of "lazy" coding (forgive me, I want to help you!) brings to future issues (code is hard to read and to debug) and, indirectly, security concerns ("lazy" code is often flawed). Fix everything that fires up a notice. :)
And, if you can, learn some more advanced PHP: go for object-oriented programming, encapsulation, information hiding, etc... This is how things are done nowadays and they work better than before. Old PHP scripts, built around notice suppression and register_globals, were somewhat dump.
The reason for the notice is because you have an "undefined constant." If you do not put quotes around an intended string, php will treat it as a constant. If it's not defined, php treats it as a strong. Take the following example:
$array = array(
'one' => 'right'
, 'two' => 'wrong'
);
define('one', 'two');
echo $array[one]; //echoes "wrong"
Also, you will get a notice if you try to access a key in an array that is not defined (such as $array['three']; above). PHP is nice enough to do this for you as other languages will error out (or worse).
The notices are not just to bug you. They are to let you know there's a problem in your code that you should strongly consider addressing.
Sounds like your error reporting level differs between machines. Compare the error_reporting levels in your php.ini's across machines.
It sounds like you have a different error_reporting value set on the two servers. Check your php.ini and set accordingly.

Hundreds of Notices and Warnings in PHP code

I've inherited some legacy code, within which if I turn on:
error_reporting(E_ALL);
I get literally hundreds of messages all over our site, all of them like:
Warning: include_once() [function.include]: Failed opening '../inc/variables.php' for inclusion (include_path='.:/usr/local/lib/php') in /var/www/html/xyz/xyz/xyz/payment.class.php on line 9
Notice: Undefined index: validateArrayName in /var/www/html/xyz/xyz/xyz/payment.class.php on line 3417
Notice: Undefined variable: objInstructor in /var/www/html/xyz/xyz/xyz/classes/metatags_class.php on line 44
Is this a bad thing? The site works fine otherwise, but I'm wondering if its
(a) a really bad thing and
(b) even if not, is it worthwhile to go fix all these issues?
There is lots of things you cannot test from the UI of an application. Stuff that happens under the hood. Unless your application is fully Unit-Tested or Functional Tested, you are likely not seeing the whole picture by clicking yourself through it.
You should definitely look into the Warnings. The developer probably didnt include variables.php for fun, so you should double check that payment.php works as expected.
Notices are less severe but they are still indicators of sloppy code. Usually, they are not that hard to fix, so unless you are on a very tight budget, fix them.
You also might want to change error_reporting from E_ALL to -1. That will enable all erros plus E_STRICT errors and anything that might be added to PHP in later versions.
The site works fine otherwise
Hmm, the failing include_once() does not ruin anything? In that case (i.e., you're not using anything - variables, globals, functions - from ../inc/variables.php) just remove the line.
You can probably ignore notices ("ugly" code), but should keep an eye on warnings (missing functionality). For legacy code always balance effort and benefit. If it works (and you're willing to accept potential security breaches), let it run ... but phase it out over time. If you're not that confident, rewrite.
Try finding where the file ../inc/variables.php is present (it is not present at /var/www/html/xyz/xyz/xyz/inc/variables.php where it is supposed to be), since the file /var/www/html/xyz/xyz/xyz/payment.class.php is trying to include it. I have a hunch that this file contains the definitions (initializations) of all the variables you are seeing in the warnings.
If after including the correct variables.php file, you get the same 'Undefined variable' warnings, in my opinion there is no need to go and modify 'legacy code' to define all the variables.
See how it goes.
Are you sure your site works fine? Do you have a good unittest suite that's run regularly to make ABSOLUTELY sure?
Failed file includes are almost always bugs (or truly horrible coding practice). If your set ever does unexplained or weird things, these problems are likely the cause. If it really has so many problems, are you sure it wouldn't be faster to rewrite it in a clean, consistent, careful style?
In general, yes you should fix these problems if you intend to continue developing this code base. If it's an orphan project or you expect to rewrite from the ground up, don't bother.

Some advice for if I should even bother eliminating Notice errors in Joomla

I changed the option in the Joomla configuration section to show all errors (E_ALL) and my component is basically unusable.
As an example, in a view (editapp) I have a template, default.php, which contains things like:
<input class="text_area" type="text" name="application_name" id="application_name" size="50" maxlength="250" value="<?php echo $item->application_name" ?> />
Now because of $item->application_name when I run this the first time (a new record), there will be notice errors everywhere Trying to get property of non-object
This is because the same template is used for saving and editing. I followed tutorials and they seemed to do it this way.
What is the go here with PHP development. Should I be checking these things? if(isset($item-)) {...}, what is the best practice for PHP development?
I agree with the others - go for no errors. In fact, I suggest going beyond E_ALL and adding in E_STRICT, which is how I do all my development. There are good reasons for each of those notices, and you'll do well to be rid of them. The most notable reason is that the notices typically point out small bugs that can make it much harder to find and fix bigger bugs down the road. It's not too different from the idea of using assertions: they help you squish bugs as quickly as possible.
As to your specific example, rather than using isset() right before referencing it, I recommend initializing the object to a sane base state going into the page (perhaps using isset() at that point). For example, you might set the application_name value to an empty string. This will enable you to keep your output statement nice and clean but properly address the notice by making sure the variable is initialized before using it. (FWIW, in many languages, using unitialized variables causes an even more aggressive response in the form of a compile-time error.)
It is absolutely worth getting rid of the errors and warnings in your code for a couple reasons:
Every error gets written to the error log. If they're inconsequential, you've polluted your error log with information that's in no way helpful.
Most warnings are indicative of bigger errors. The unset variable you're referencing can cause problems down the road in situations you may not have thought of.
Others who are using your template may not have the ability or knowledge to turn off errors, resulting in them not using your code.

Categories