I'm wondering what errors are considered fatal vs. not in PHP (though interested in other languages too). Is there a concise explanation and/or listing of each somewhere of error types? Does using the expression "non-fatal" even make sense?
The reason I'm wondering is because sometimes when I make PHP errors my $_SESSION (actually using codeigniter sessions) is destroyed whereas in other cases it is not and I can't quite put my finger on why this is happening.
Well, the naming is pretty self-explanatory:
Fatal errors are critical errors and it means that the parser cannot possibly continue to parse the rest of your code, because of this error. For example:
Your webserver has run out of memory to parse the script (e.g. parser hit the memory_limit set in php.ini).
The script contains an infinite loop (e.g. while(1) { echo "Hi friend!"; } and runs longer than the set max_execution_time in your php.ini).
Non-fatal errors are usually called Warnings, they are still pretty serious and should be fixed, but do not cause the parser to stop parsing your code, it can still continue, regardless of the error that occurred. For example:
You are calling unset variables.
You are requesting a key in an array that does not exist.
You are calling an non-existing function.
Hope this clears things up a bit for you.
Related
First off I know this question has gone around more than once here:
Why should I fix E_NOTICE errors?
Why should I fix E_NOTICE errors? Pros and cons
But the more that I fix all E_NOTICEs (as people say you should) the more I notice that:
I am micro-optimising
I am actually making more code and making my code harder to mantain and slower
Take an example:
Say your using the MongoDB PHP driver and you have a MongoDate object in a class var named ts within a class that represents a single row in a collection in your database. Now you acces this var like: $obj->ts->sec but PHP throws a fit (E_NOTICE) because ts in this case is not defined as an object in itself because this particular row does not have a ts field. So you think this is OK, this is desired behaviour, if it's not set return null and I will take care of it myself outside of the interpreters own robotic workings (since you wrap this in a date() function that just returns 1970 if the var is null or a none-object).
But now to fix that E_NOTICE as another developer really wants me to since having ANY E_NOTICEs is terribad and it makes the code slower to not do it according to the errors. So I make a new function in the $obj class called getTs and I give it 3 lines, literally to do nothing but check if the ts var is a MongoDate object and return it if it is...
WHY? Can't PHP do this perfectly fine for me within its much faster interpreter than having to do it within the runtime of the app itself? I mean every where I am having to add useless bumpth to my code, pretty much empty functions to detect variables that I actually just handle with PHPs own ability to return null or checking their instanceof when I really need to (when it is vital to the operation and behaviour of the said function) and don't get me started on the isset()s I have added about 300 lines of isset()s, it's getting out of hand. I have of course got to make this getTs functions because you can't do:
class obj{
public $ts = new MongoDate();
}
I would either have to store the ts within the __constructor (which I am not too happy about either, I am using a lot of magics as it is) or use a function to detect if it's set (which I do now).
I mean I understand why I should fix:
Undefined vars
Assigning properties of unset vars (null vars)
constant errors etc
But if you have tested your code and you know it is safe and will only work the way you desire what is the point in fixing all of the undefined index or none-object errors? Isn't adding a bunch of isset()s and 2 lines functions to your code actually micro-optimisation?
I have noticed after making half my site E_NOTICE compliant that actually it uses more CPU, memory and time now...so really what's the point of dealing with every E_NOTICE error and not just the ones that ARE errors?
Thanks for your thoughts,
You do certainly do get better performance by using isset(). I did some benchmarks, not too long ago, and just hiding errors came out to be about 10x slower.
http://garrettbluma.com/2011/11/14/php-isset-performance/
That said, performance usually isn't a critical factor in PHP. What does, personally drive me crazy is silent errors.
When the interpreter chooses to not flag something as an error (which could lead to instability) is a huge problem. PHP in particular has a tendency to
warn about things that should error (e.g. failure to connect to database) and
issue notices about things that ought to warn (e.g. attempting to access a member of a null object).
Perhaps I'm just overly opinionated about this kind of stuff but I've been bitten before by these silent errors. I recommend always including E_NOTICE in error reporting.
Whether or not you should fix them is certainly debatable, and will just depend on the return in your situation; eg, it's more important if the code will have a longer life-span, more devs, etc.
In general, assuming that your functions will be used (and mis-used) by someone else is the best practice, so you should do isset/!empty/is_object checks to account for this. Often, your code will find it's way into uses and situations you never intended it for.
As far as performance, Every time any kind of error is thrown--E_NOTICE included--the interpreter spins up the error handler, builds a stack trace, and formats the error. The point is that, whether or not you have them reporting, errors always slow execution; therefore, 2-3 function calls to avoid an E_NOTICE will still improve your performance.
Edit:
Alternatives for the above example
I wouldn't necessarily create extra objects to avoid the errors; you can gracefully avoid them without. Here are a couple of options:
1) Function that handles missing ts:
SpecialClass class {
funciton getTs () {
return !empty($this->ts) ? $ts->sec : false;
}
}
2) Deal with missing ts in template/procedure:
if (!empty($obj->ts->sec)) {
//do something
}
I particularly like empty() because you can use it to replace of (isset($var) && ($var or 0 != $var //etc)), saving multiple calls/comparisons and empty never throws notices for the target var or attribute. It will throw an error if you're calling it on a proptery/member of a non-existent variable.
So I'm working on cleanup of a horrible codebase, and I'm slowly moving to full error reporting.
It's an arduous process, with hundreds of notices along the lines of:
Notice: Undefined index: incoming in /path/to/code/somescript.php on line 18
due to uses of variables assuming undefined variables will just process as false, like:
if($_SESSION['incoming']){
// do something
}
The goal is to be able to know when a incorrectly undefined variable introduced, the ability to use strict error/notice checking, as the first stage in a refactoring process that -will- eventually include rewriting of the spots of code that rely on standard input arrays in this way. There are two ways that I know of to replace a variable that may or may not be defined
in a way that suppresses notices if it isn't yet defined.
It is rather clean to just replace instances of a variable like $_REQUEST['incoming'] that are only looking for truthy values with
#$_REQUEST['incoming'].
It is quite dirty to replace instances of a variable like $_REQUEST['incoming'] with the "standard" test, which is
(isset($_REQUEST['incoming'])? $_REQUEST['incoming'] : null)
And you're adding a ternary/inline if, which is problematic because you can actually nest parens differently in complex code and totaly change the behavior.
So.... ...is there any unacceptable aspect to use of the # error suppression symbol compared to using (isset($something)? $something : null) ?
Edit: To be as clear as possible, I'm not comparing "rewriting the code to be good" to "#", that's a stage later in this process due to the added complexity of real refactoring. I'm only comparing the two ways (there may be others) that I know of to replace $undefined_variable with a non-notice-throwing version, for now.
Another option, which seems to work well with lame code that uses "superglobals" all over the place, is to wrap the globals in dedicated array objects, with more or less sensible [] behaviour:
class _myArray implements ArrayAccess, Countable, IteratorAggregate
{
function __construct($a) {
$this->a = $a;
}
// do your SPL homework here: offsetExists, offsetSet etc
function offsetGet($k) {
return isset($this->a[$k]) ? $this->a[$k] : null;
// and maybe log it or whatever
}
}
and then
$_REQUEST = new _myArray($_REQUEST);
This way you get back control over "$REQUEST" and friends, and can watch how the rest of code uses them.
You need to decide on your own if you rate the # usage acceptable or not. This is hard to rate from a third party, as one needs to know the code for that.
However, it already looks like that you don't want any error suppression to have the code more accessible for you as the programmer who needs to work with it.
You can create a specification of it in the re-factoring of the code-base you're referring to and then apply it to the code-base.
It's your decision, use the language as a tool.
You can disable the error suppression operator as well by using an own callback function for errors and warnings or by using the scream extension or via xdebug's xdebug.scream setting.
You answered you question yourself. It suppress error, does not debug it.
In my opinion you should be using the isset() method to check your variables properly.
Suppressing the error does not make it go away, it just stops it from being displayed because it essentially says "set error_reporting(0) for this line", and if I remember correctly it would be slower than checking isset() too.
And if you don't like the ternary operator then you should use the full if else statement.
It might make your code longer but it is more readable.
I would never suppress errors on a development server, but I would naturally suppress errors on a live server. If you're developing on a live server, well, you shouldn't. That means to me that the # symbol is always unacceptable. There is no reason to suppress an error in development. You should see all errors including notices.
# also slows things down a bit, but I'm not sure if isset() is faster or slower.
If it is a pain to you to write isset() so many times, I'd just write a function like
function request($arg, $default = null) {
return isset($_REQUEST[$arg]) ? trim($_REQUEST[$arg]) : $default;
}
And just use request('var') instead.
Most so-called "PHP programmers" do not understand the whole idea of assigning variables at all.
Just because of lack of any programming education or background.
Well, it isn't going a big deal with usual php script, coded with considerable efforts and consists of some HTML/Mysql spaghetti and very few variables.
Another matter is somewhat bigger code, when writing going to be relatively easy but debugging turns up a nightmare. And you are learn to value EVERY bloody error message as you come to understanding that error messages are your FRIENDS, not some irritating and disturbing things, which better to be gagged off.
So, upon this understanding you're learn to leave no intentional errors in your code.
And define all your variables as well.
And thus make error messages your friends, telling you that something gone wrong, lelping to hunt down some hard-spotting error which caused by uninitialized variable.
Another funny consequence of lack of education is that 9 out of 10 "PHP programmers" cannot distinguish error suppression from turning displaying errors off and use former in place of latter.
I've actually discovered another caveat of the # beyond the ones mentioned here that I'll have to consider, which is that when dealing with functions, or object method calls, the # could prevent an error even through the error kills the script, as per here:
http://us3.php.net/manual/en/language.operators.errorcontrol.php
Which is a pretty powerful argument of a thing to avoid in the rare situation where an attempt to suppress a variable notice suppressed a function undefined error instead (and perhaps that potential to spill over into more serious errors is another unvoiced reason that people dislike #?).
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
I'm making a web application that uses URL queries to access different parts of the application. I was looking for a solution to make an invalid query like index.php?page=dashboarrrd display an error 404 message instead of a PHP error.
After some searching, I found that I could use something like the following to do the job:
if(!#include($fileName)){
#include("pageData/404.php");
}
And that makes sense, but I don't know why that works. I mean, what the heck does the # before the include mean? I totally understand include $filename; but I need an explanation for #include ($fileName)
the code you really need is
$fileName = "pagedata/".basename($_GET['page']).".php";
if(is_readable($fileName)) {
include($fileName);
} else {
include("pagedata/404.php");
}
and # has absolutely nothing to do here
# is one of biggest delusions coming from lack of experience.
Ones who using it do expect only one kind of error, while in fact there can be many more. And to gag ALL possible messages to suppress only one of them is definitely like to throw out the child along with the bath.
There is a fundamental problem that makes such misunderstanding so widespread:
Most PHP users cannot distinguish three sides of error control:
error handling
error reporting
user notification.
Most of time in sake of [3] people mess with (1) and (2). While each of them require separate treatment:
your program should raise no intentional errors. No error should be part of program logic. All errors that ever raised should be only unexpected ones.
if you expect some error, you have to handle it. Not gag with #, but gracefully handle. is_readable() in my code exactly for that.
error reporting is for the programmer and should be always at max. So, error logging should be enabled on a live site and a programmer have to check all errors occurred. And of course he would be interested in such errors, thus # will do only harm here.
User-level error messages should be different from system ones. Your 404.php is a good example of such user-friendly behavior. As for the system error messages, a user shouldn't be able to see them at all. Just turn display_errors off and see - there is no use for the # again!
This is the # Error Control Operator (quoting) :
When prepended to an expression in
PHP, any error messages that might be
generated by that expression will be
ignored.
In normal conditions, if include cannot load the file you've passed as a parameter, it'll emit a warning.
Prepending the # operator to include will prevent that warning from being emited -- and, so, from being displayed / logged.
So, the following portion of code :
include 'does-not-exist.php';
Will get you the following warnings :
Warning: include(does-not-exist.php) [function.include]: failed to open stream: No such file or directory
Warning: include() [function.include]: Failed opening 'does-not-exist.php' for inclusion
While this line :
#include 'does-not-exist.php';
Will get you not warning.
And, as a sidenote, for information : Five reasons why the shut-op operator (#) should be avoided
The # suppresses errors. This is generally discouraged, as when developing you want to see errors.
Errors are easy to suppress when moving to a production environment with the display_errors setting to off. So yea, in most cases, there really is no need for the error to be suppressed.
EDIT
As an extra tidbit to "improve" that, what I used to do when dynamically including a file, is have an array which acts as a "white list" of valid requests. This does not "have" to be an array, just what I chose to do an example with.
$whiteList = array('filename1', 'index', 'home', 'about');
if (in_array($filename, $whiteList)) {
include($filename);
}else {
include('page/404.php');
}
This would do a few things, 1 make you not need the error suppressor. Two, it would make it a bit more securer, as without this, you would need to do a basename call to filter the text to prevent certain type of include injections etc. (Not knowing if you did this already, just extra information).
So yea, you may want analyze / look at other ways to achieve this and above is just one method :)
The use of "#" simply suppresses the error that would normally result from (in this instance) a missing file. Whilst generally its use is a very bad idea, there are some rare exceptions, such as the code snippet you provide above.
For more information, see the Error Control Operators section of the PHP manual.
Additionally, you might find the existing Reference - What does this symbol mean in PHP? question worthy of a quick scan.
The # in php suppresses all error output. For instance, if you had error reporting for warnings, an # in front of a function that generated a warning would not display the warning text.
include is an example of such a construct. If the included file is not found, it will display a warning saying so. The # is not necessary in the code at all, it is just there so that the user will not see warnings.
However, it is better to use apache (or php if you prefer) to change ini for displaying errors on the development site and not displaying them on the production site. That would make the # symbol useless.
A better question is why you need to do this 404 include. Why are you including a file for display? Why not have apache handle 404 redirects on its own? Why wouldn't the file exist in the first place?
# suppresses error messages. The parentheses are optional in include, but whoever wrote that snippet included them.
#include() is the opposite of require(). The first will silently ignore an (optional and missing) include script, while the second will throw an error and halt the script when the (critical) dependency is missing.
In this instance it is only senseful within the if(). The second should preferrably not have an error suppression, as it doesn't mask any seriously security-relevant error message.
There are many functions (well most really) in the PHP language that get all upset and throw warnings and notices when they don't like something about their input - rather than just returning FALSE (though they do that too).
One place this is really common is in the GD and string functions. They are very particular about their arguments and it's really easy for user input to fail meeting their standards.
For example, a user uploads a image that is corrupt (intentionally or unintentionally). Resulting in warnings from the GD library.
So far there are only three ways I have found to silence PHP on this issue:
Change your error reporting setting in the ini or at runtime (yuck).
Suppress errors with the slow # symbol.
Change error reporting right before/after the function:
like so:
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
Naturally, the second two choices just make me sick. Which leaves me using 1) and toning down the PHP error settings. However, I want PHP to be in strict mode so that while I'm working I can catch logic bugs and bad form that might creep into my code. However, I don't want to have random errors thrown when PHP doesn't like something.
So is there any way to separate errors that are from malformed arguments (bad input) from errors that are from bad programming? For example:
If a user image is invalid just return FALSE and I'll deal with it. I don't need warnings.
If my passing of an image resource to print function is invalid throw warnings.
There's another alternative - use set_error_handler(), you can even call it just before the GD function call and return to the default with restore_error_handler().
There's a good comment in the question try and catch a warning that gives more detail on how this is accomplished.
This is an ill-design from the beginnings of PHP. A modern PHP library would throw an exception on error. And an exception may be caught. But back then GD was written PHP didn't yet support exceptions.
Thus I think that in this case it is legitimate to use the # operator.
Fix the code
Sanitize the input before you call the functions. This saves you errors.
There is no generic approach for all libraries besides editing the offending library and changing how it throws exceptions. Honeslty, a lot of PHP devs really didn't care about exceptions being thrown, but now more and more people are getting on the E_STRICT wagon. When the GD libs were generated the mentality probably was that throwing uncatchable errors wasn't that big a deal.
As far as the validating images with GD. The only thing you can really do is to use a different library or function to validate your images. You might try using magic byte functions to check if the images have proper headers(though this doesn't mean the rest of the file is structured correctly). At least using the magic byte functions will take care of obvious things like someone uploading a text file instead of a JPEG.
If there is something like that, you can use the #-operator
Its not a clean solution, but there are situations, where it's indispensable.
Did you check the image before using getimagesize() ?
However, I don't want to have random
errors thrown when PHP doesn't like
something.
Why not? PHP is trying to tell you something notable with warnings and notices. In the GD example you'll want to log when a user is uploading a corrupt file - especially if it's being used in an attack. Turn of the display of error messages and log everything.
Python's convention is that variables are created by first assignment, and trying to read their value before one has been assigned raises an exception. PHP by contrast implicitly creates a variable when it is read, with a null value. This means it is easy to do this in PHP:
function mymodule_important_calculation() {
$result = /* ... long and complex calculation ... */;
return $resukt;
}
This function always returns null, and if null is a valid value for the functuion then the bug might go undetected for some time. The Python equivalent would complain that the variable resukt is being used before it is assigned.
So... is there a way to configure PHP to be stricter with variable assignments?
PHP doesn't do much forward checking of things at parse time.
The best you can do is crank up the warning level to report your mistakes, but by the time you get an E_NOTICE, its too late, and its not possible to force E_NOTICES to occur in advance yet.
A lot of people are toting the "error_reporting E_STRICT" flag, but its still retroactive warning, and won't protect you from bad code mistakes like you posted.
This gem turned up on the php-dev mailing-list this week and I think its just the tool you want. Its more a lint-checker, but it adds scope to the current lint checking PHP does.
PHP-Initialized Google Project
There's the hope that with a bit of attention we can get this behaviour implemented in PHP itself. So put your 2-cents on the PHP mailing list / bug system / feature requests and see if we can encourage its integration.
There is no way to make it fail as far as I know, but with E_NOTICE in error_reporting settings you can make it throw a warning (well, a notice :-) But still a string you can search for ).
Check out error reporting, http://php.net/manual/en/function.error-reporting.php
What you want is probably E_STRICT. Just bare in mind that PHP has no namespaces, and error reporting becomes global. Kind of sucks to be you if you use a 3rd party library from developers that did not have error reporting switched on.
I'm pretty sure that it generates an error if the variable wasn't previously declared. If your installation isn't showing such errors, check the error_reporting() level in your php.ini file.
You can try to play with the error reporting level as indicated here: http://us3.php.net/error_reporting but I'm not sure it mention the usage of non initiated variable, even with E_STRICT.
There is something similar : in PHP you can change the error reporting level. It's a best practice to set it to maximum in a dev environnement. To do so :
Add in your PHP.ini:
error_reporting = E_ALL
Or you can just add this at the top of the file your are working on :
error_reporting(E_ALL);
This won't prevent your code from running but the lack of variable assignments will display a very clear error message in your browser.
If you use the "Analyze Code" on files, or your project in Zend Studio it will warn you about any uninitialized variables (this actually helped find a ton of misspelled variables lurking in seldom used portions of the code just waiting to cause very difficult to detect errors). Perhaps someone could add that functionality in the PHP lint function (php -l), which currently only checks for syntax errors.