72

In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?

If so, in what circumstances would you use this?

Code examples are welcome.

Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to use

@fopen($file);

and then check afterwards... but you can get rid of the @ by doing

if (file_exists($file))
{
    fopen($file);
}
else
{
    die('File not found');
}

or similar.

I guess the question is - is there anywhere that @ HAS to be used to supress an error, that CANNOT be handled in any other manner?

VolkerK
  • 92,020
  • 18
  • 157
  • 222
Mez
  • 22,526
  • 14
  • 67
  • 91
  • 6
    Your example doesn't work; "File not found" is not the only way fopen() can fail. Perhaps the file isn't readable. Perhaps it's open by another process. The error conditions are platform-dependent and anyway you might not want to spend time thinking up failure cases. – Jason Cohen Sep 26 '08 at 01:45
  • see also: http://stackoverflow.com/questions/1087365 – dreftymac Oct 11 '11 at 17:33
  • 4
    and why the hack this question closed ?? – Akshaydeep Giri May 04 '13 at 18:11

17 Answers17

124

Note: Firstly, I realise 99% of PHP developers use the error suppression operator (I used to be one of them), so I'm expecting any PHP dev who sees this to disagree.

In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?

Short answer:
No!

Longer more correct answer:
I don't know as I don't know everything, but so far I haven't come across a situation where it was a good solution.

Why it's bad:
In what I think is about 7 years using PHP now I've seen endless debugging agony caused by the error suppression operator and have never come across a situation where it was unavoidable.

The problem is that the piece of code you are suppressing errors for, may currently only cause the error you are seeing; however when you change the code which the suppressed line relies on, or the environment in which it runs, then there is every chance that the line will attempt to output a completely different error from the one you were trying to ignore. Then how do you track down an error that isn't outputting? Welcome to debugging hell!

It took me many years to realise how much time I was wasting every couple of months because of suppressed errors. Most often (but not exclusively) this was after installing a third party script/app/library which was error free in the developers environment, but not mine because of a php or server configuration difference or missing dependency which would have normally output an error immediately alerting to what the issue was, but not when the dev adds the magic @.

The alternatives (depending on situation and desired result):
Handle the actual error that you are aware of, so that if a piece of code is going to cause a certain error then it isn't run in that particular situation. But I think you get this part and you were just worried about end users seeing errors, which is what I will now address.

For regular errors you can set up an error handler so that they are output in the way you wish when it's you viewing the page, but hidden from end users and logged so that you know what errors your users are triggering.

For fatal errors set display_errors to off (your error handler still gets triggered) in your php.ini and enable error logging. If you have a development server as well as a live server (which I recommend) then this step isn't necessary on your development server, so you can still debug these fatal errors without having to resort to looking at the error log file. There's even a trick using the shutdown function to send a great deal of fatal errors to your error handler.

In summary:
Please avoid it. There may be a good reason for it, but I'm yet to see one, so until that day it's my opinion that the (@) Error suppression operator is evil.

You can read my comment on the Error Control Operators page in the PHP manual if you want more info.

halfer
  • 18,701
  • 13
  • 79
  • 158
Gerry
  • 9,339
  • 3
  • 36
  • 47
  • 23
    This is absolutely correct. Suppressing errors is a fundamental mistake. Use your error handler, or use exceptions, don't hide the error. – MattBelanger Jun 11 '09 at 16:20
  • 1
    Even "isset" is faster than "@",i still prefer using "@": $_LOG_TYPES=array('request', 'click'); $t1=time().substr(microtime(),2,6); for ($i=0;$i<10000;++$i) {$log_type=in_array(@$_GET['log_type'], $_LOG_TYPES)?$_GET['log_type']:'unknown'; } $t2=time().substr(microtime(),2,6); echo 'time_length:'.((float)$t2-(float)$t1); $t1=time().substr(microtime(),2,6); for ($i=0;$i<10000;++$i) {$log_type=in_array(isset($_GET['log_type'])?$_GET['log_type']:null, $_LOG_TYPES)?$log_type:'unknown'; } $t2=time().substr(microtime(),2,6); echo 'time_length:'.((float)$t2-(float)$t1); – diyism Aug 26 '11 at 04:23
  • 13
    `-1` for parroting a silly "is evil" meme. Eschewing a built-in language feature with explicit disregard for the actual use case is the prime definition of cargo cult programming. -- In particular this rant fails to mention that suppressed errors are not factually gone. A custom error handler can still revive them (`set_error_handler("var_dump");` is a lazy equivalent of the scream extension). Moreover such overbroad advisories lead to the commonplace `isset()` notice suppression syntax workarounds, which actually can obstruct debugging (as the debug notices are then suppressed irretrievably). – mario Oct 24 '11 at 14:57
  • 4
    @mario "with explicit disregard for the actual use case"... hmmmm.. maybe you didn't read the full text of "is evil". "There may be a good reason for it, but I'm yet to see one, so until that day it's my opinion that the (@) Error suppression operator is evil". I was saying I was yet to find such a context. It seems like you have an answer for the question the Op asked, perhaps you might consider submitting one where there would be more room to discuss your views. – Gerry Oct 26 '11 at 15:06
  • 1
    I disagree. @ is fine for handling forms. For example, you may wish to suppress notices as short-hand using user-submitted variables, like: if (@$_POST['test'])... PHP notices that are set to be shown can throw off things like JSON response bodies and HTML design. This is still an 'error', but it's not an "evil" error or a problem with your code. – Lee Benson Apr 10 '12 at 08:11
  • 3
    Your code doesn't check the index exists before checking it's value. This will lead to hard to track down issues, say if a form element is renamed or mistyped. A non existent index means something different to a form element left blank. Also you shouldn't be displaying errors to end users. If you are just having HTML/JSON problems in development and think it's fine to leave them, this is where we disagree. Notices on a typical execution path generally indicate a failure to handle conditions you should be handling. – Gerry Apr 23 '12 at 21:41
  • I totally agree with you, however I think I have found one situation when `@` seems to be the best solution. It is with `stat()` - take a look [here](http://stackoverflow.com/questions/18325572/php-phar-file-exists-issue) and check my answer and tell me if you disagree with me that it cannot be avoided. – Zaffy Aug 27 '13 at 16:09
  • 1
    I disagree that there is no acceptable usage case. sometimes, you need need to assign a value of a superglobal to a variable, with get being the primary place this problem will arise. obviously, you can't say `$_GET = null`,because it may contain other variables you need.isset is impractical for multiple gets in a single view. solution? a one line wonder for each of your maybe present variables: `@$foo = $_GET['foo'] or NULL;` then, you have logic to check whether each variable is empty with `empty()`. best solution for this use case requires `@` to suppress the meaningless warning. – r3wt Jun 25 '14 at 08:33
  • @Zaffy The problem appears to be that file_exists wasn't working for a particular case, but I think that Mark Wu pointed out the reason and the fix. @r3wt It was hard to follow, but are you saying that you want to do: `@$foo = $_GET['foo'] or NULL;` instead of `$foo = isset($_GET['foo']) ? $_GET['foo'] : NULL;`? – Gerry Apr 10 '15 at 15:11
  • Using `empty($var)` when the variable definitely exists is silly, just use `!$var` when you know it exists. `empty($var)===(!isset($var)||!$var)`. If you want to avoid undefined errors when pulling values from an array, try this `$_GET+=['key1'=>'','key2'=>'','key3'=>''];` this way, any parameters that weren't passed will be filled in with whatever value you provide. – Chinoto Vokro Feb 26 '16 at 17:08
  • If you want to check for the existence of multiple keys, then instead of `if (!isset($_GET['key1'],$_GET['key2'],$_GET['key3'])) {/*error*/}`, you could use `if (array_diff_key(array_flip(['key1','key2','key3'),$_GET)) {/*error*/}`. What happens is the first array gets turned into `['key1'=>0,'key2'=>1,'key3'=>2]` and then any keys that are also in $_GET are removed, if array_diff_key() returns an empty array (which is treated as false), you're good to go. If the array name length is short and you don't need to check many keys, isset() is shorter, but can be much longer otherwise. – Chinoto Vokro Feb 26 '16 at 17:30
  • 1
    @Gerry: You were right. Hope that helps others: had an @ on an include statement and when the app would crash at times, nothing would get logged in php error log. Reason is there was an @ on an include spans MUCH more than the if it was included successfully or not, only but also applies to functions coming from a suppressed "include", they will NOT log errors when you call them later on. No more @ on includes for me. – Wadih M. Feb 16 '17 at 02:13
  • I will give you a good reason. If you have to delete a group of files with `glob` and `unlink` and you don't care if files actually exist on disk and you don't want to have your logs filled with `No such file or directory`, then `@` is what you need. – Viktor Joras Jul 09 '17 at 07:13
  • @ViktorJoras do an exists check before unlink. There may be 0.001% of time where a file is deleted between these two checks and you end up with a single log entry. This is far better than the situation you will run into where you accidentally suppress an error you want to know about but never predicted would happen when you added `@`. – Gerry Jul 09 '17 at 07:35
  • @Gerry there are situations where you don't really care about the function's overcome and you don't want to know if function is failing for no reason in the world. `@` is meant for these very situations. – Viktor Joras Jul 09 '17 at 07:46
  • @ is something that wouldn't be used until needed. Example, when there are no other ways to avoid a warning that you don't care, other than suppressing it: echo @convert_uudecode('hello'); – xam Jun 05 '18 at 17:45
26

I would suppress the error and handle it. Otherwise you may have a TOCTOU issue (Time-of-check, time-of-use. For example a file may get deleted after file_exists returns true, but before fopen).

But I wouldn't just suppress errors to make them go away. These better be visible.

Paweł Hajdan
  • 16,853
  • 9
  • 45
  • 63
  • 9
    The problem with that is that you end up suppressing other errors that you didn't predict and then spend your entire day trying to track down a bug that isn't throwing any errors. In the rare situation of a TOCTOU issue I think it's far better for an error to be thrown as PHP errors should not be displayed to end users anyway, but it will still allow somebody to be aware of the situation through logging of errors or displaying it if the script is running in a development environment. Error supression is the best way to hide a problem. (eg. files being deleted :) ) – Gerry Jun 06 '09 at 17:09
  • 8
    This is fine, but for the love of not being hunted down and murdered, please check for the right error. I once spent way too long tracking down a database problem - I was seeing Close() failures, and nothing was working. Eventually I discovered that the genious @'d the initial connection, and the "else" check was essentially empty. Removing the @, I was immediately able to discern that the connection credentials were bad. – anonymous coward Jun 11 '09 at 16:23
21

Yes suppression makes sense.

For example, the fopen() command returns FALSE if the file cannot be opened. That's fine, but it also produces a PHP warning message. Often you don't want the warning -- you'll check for FALSE yourself.

In fact the PHP manual specifically suggests using @ in this case!

Jason Cohen
  • 75,915
  • 26
  • 104
  • 111
  • 3
    but, surely, this can be avoided by checking file_exists($file) first? – Mez Sep 26 '08 at 01:03
  • 14
    No it can't, there are other failure conditions such as "no permissions to read" or "file busy." – Jason Cohen Sep 26 '08 at 01:46
  • 3
    That's great until fopen throws an error you weren't anticipating. You can't check for all of your known error conditions? Create an fopen wrapper function. – Gerry Jan 28 '12 at 04:49
  • I was tempted to plus you 1 just because you are Jason Cohen. Great answer/comment. – Marco Demaio Feb 22 '13 at 14:57
  • @JasonCohen What about https://secure.php.net/is_readable? There is still a race condition however... – John M. Nov 03 '15 at 23:50
  • If you have to worry about race conditions, you may have bigger problems to worry about (though I'm thinking of things like including dynamically generated/deleted php files, which is a terrible idea). – Chinoto Vokro Feb 26 '16 at 17:35
13

If you don't want a warning thrown when using functions like fopen(), you can suppress the error but use exceptions:

try {
    if (($fp = @fopen($filename, "r")) == false) {
        throw new Exception;
    } else {
        do_file_stuff();
    }
} catch (Exception $e) {
    handle_exception();
}
dirtside
  • 7,666
  • 9
  • 40
  • 52
  • 5
    If you are throwing an exception then you don't strictly need the `else`, just `do_file_stuff()`. – MrWhite Jan 21 '14 at 16:08
7

I NEVER allow myself to use '@'... period.

When I discover usage of '@' in code, I add comments to make it glaringly apparent, both at the point of usage, and in the docblock around the function where it is used. I too have been bitten by "chasing a ghost" debugging due to this kind of error suppression, and I hope to make it easier on the next person by highlighting its usage when I find it.

In cases where I'm wanting my own code to throw an Exception if a native PHP function encounters an error, and '@' seems to be the easy way to go, I instead choose to do something else that gets the same result but is (again) glaringly apparent in the code:

$orig = error_reporting(); // capture original error level
error_reporting(0);        // suppress all errors
$result = native_func();   // native_func() is expected to return FALSE when it errors
error_reporting($orig);    // restore error reporting to its original level
if (false === $result) { throw new Exception('native_func() failed'); }

That's a lot more code that just writing:

$result = @native_func();

but I prefer to make my suppression need VERY OBVIOUS, for the sake of the poor debugging soul that follows me.

ashnazg
  • 6,081
  • 2
  • 28
  • 36
  • 1
    This is an opinion and not a very good one. You can accomplish the same thing with $result = @native_func(); and if($result) w/o that ugly ass mess. I agree @ is bad, but only if its not handled. – Mfoo Mar 12 '15 at 10:30
  • Do you think, it is more kosher than @fopen? You also disables the error reporting but with more code and greater execution time. IIRC try...catch will not work due to it is warning not error... try...catch will be one kosher solution in this case. It is hiding NetBeans warning only... – 18C Dec 09 '17 at 03:10
  • The problem I'm trying to solve here is highlighting to the next developer that suppression is being done. I choose to sacrifice lines of code, micro-optimized execution time, and presumed ugliness in order to achieve my goal. I don't see a "one best way" that covers all needs, so this is how I choose my trade-offs. – ashnazg Dec 09 '17 at 14:34
6

Error suppression should be avoided unless you know you can handle all the conditions.

This may be much harder than it looks at first.

What you really should do is rely on php's "error_log" to be your reporting method, as you cannot rely on users viewing pages to report errors. ( And you should also disable php from displaying these errors )

Then at least you'll have a comprehensive report of all things going wrong in the system.

If you really must handle the errors, you can create a custom error handler

http://php.net/set-error-handler

Then you could possibly send exceptions ( which can be handled ) and do anything needed to report weird errors to administration.

Kent Fredric
  • 54,014
  • 14
  • 101
  • 148
  • I know I shouldn't supress the errors, but some things will throw an E_WARNING or an E_NOTICE, when it's not needed to actually show that to the end user, and in a lot of cases, it can be avoided to actually theow these. except, for now in the case of mysql_open – Mez Sep 26 '08 at 01:16
  • 1
    @martin meredith: thats why you use "error_log" and "display_errors=false" – Kent Fredric Sep 26 '08 at 06:35
  • @Kent - Best answer on this page by far! [edit: make that second best, because I just added one :P] @Mez - As Kent has suggested, set up an error handler that only displays errors to you. – Gerry Jun 06 '09 at 18:53
5

Most people do not understand the meaning of error message.
No kidding. Most of them.

They think that error messages are all the same, says "Something goes wrong!"
They don't bother to read it.
While it's most important part of error message - not just the fact it has been raised, but it's meaning. It can tell you what is going wrong. Error messages are for help, not for bothering you with "how to hide it?" problem. That's one of the biggest misunderstandings in the newbie web-programming world.

Thus, instead of gagging error message, one should read what it says. It has not only one "file not found" value. There can be thousands different errors: permission denied, save mode restriction, open_basedir restriction etc.etc. Each one require appropriate action. But if you gag it you'll never know what happened!

The OP is messing up error reporting with error handling, while it's very big difference!
Error handling is for user. "something happened" is enough here.
While error reporting is for programmer, who desperately need to know what certainly happened.

Thus, never gag errors messages. Both log it for the programmer, and handle it for the user.

Your Common Sense
  • 152,517
  • 33
  • 193
  • 313
3

The only place where I really needed to use it is the eval function. The problem with eval is that, when string cannot be parsed due to syntax error, eval does not return false, but rather throws an error, just like having a parse error in the regular script. In order to check whether the script stored in the string is parseable you can use something like:

$script_ok = @eval('return true; '.$script);

AFAIK, this is the most elegant way to do this.

Milan Babuškov
  • 55,232
  • 47
  • 119
  • 176
  • First off, eval() shouldn't ever be used. Second, if $script contains functions, they will be evaluated and then the second time this is run, it will complain that those functions were already defined and terminate. – Chinoto Vokro Feb 26 '16 at 17:46
3

is there not a way to suppress from the php.ini warnings and errors? in that case you can debug only changing a flag and not trying to discovering which @ is hiding the problem.

Enrico Murru
  • 2,309
  • 3
  • 21
  • 24
  • yes, you can do error_reporting (E_ALL & ~E_NOTICE & ~E_WARNING) - but I don't want to do this, see edited question – Mez Sep 26 '08 at 01:17
3

Using @ is sometimes counter productive. In my experience, you should always turn error reporting off in the php.ini or call

error_reporting(0);

on a production site. This way when you are in development you can just comment out the line and keep errors visible for debugging.

Eric Lamb
  • 1,394
  • 5
  • 16
  • 29
  • I prefer for errors to be visible. What I'm trying to work out, if is there is any way that you would have to use an @ or you might have an error, that cannot be caught before. – Mez Sep 26 '08 at 01:07
  • I've never seen an instance where using @ for error suppression was a positive thing. It hides all future errors, not just the one that you wanted to ignore. – Gerry Jun 06 '09 at 16:50
  • Don't turn error_reporting off, that's madness! While you're turning it back on, make sure it's able to log errors to a file that you can read later. The proper way to not show errors to users is via `ini_set('display_errors',0);` or better yet, directly modify the ini file to include that. – Chinoto Vokro Feb 26 '16 at 17:41
3

One place I use it is in socket code, for example, if you have a timeout set you'll get a warning on this if you don't include @, even though it's valid to not get a packet.

$data_len = @socket_recvfrom( $sock, $buffer, 512, 0, $remote_host, $remote_port )
Don Neufeld
  • 21,368
  • 10
  • 49
  • 49
2

Some functions in PHP will issue an E_NOTICE (the unserialize function for example).

A possible way to catch that error (for PHP versions 7+) is to convert all issued errors into exceptions and not let it issue an E_NOTICE. We could change the exception error handler as follow:

function exception_error_handler($severity, $message, $file, $line) {                                                                       
    throw new ErrorException($message, 0, $severity, $file, $line);          
}                                                                            

set_error_handler('exception_error_handler');                          

try {             
    unserialize('foo');
} catch(\Exception $e) {
    // ... will throw the exception here
}       
Daan
  • 6,621
  • 5
  • 36
  • 52
1

You do not want to suppress everything, since it slows down your script.

And yes there is a way both in php.ini and within your script to remove errors (but only do this when you are in a live environment and log your errors from php)

<?php
    error_reporting(0);
?>

And you can read this for the php.ini version of turning it off.

Ólafur Waage
  • 64,767
  • 17
  • 135
  • 193
  • I'm not looking for a way to turn it off, I'm looking for whether there's a reason to use it, as in anything that cannot be handled without using @ (one item so far - mysql_connect) – Mez Sep 26 '08 at 01:14
  • @Industrial it is doing extra work suppressing the errors. Since it is supposed to display an error but finds an @ there and has do deal with it dynamically. – Ólafur Waage May 23 '10 at 19:04
  • Ah! So it would then be better to follow your example - error_reporting(0);? – Industrial May 23 '10 at 19:35
1

Today I encountered an issue that was a good example on when one might want to use at least temporarily the @ operator.

Long story made short, I found logon info (username and password in plain text) written into the error log trace.

Here a bit more info about this issue.

The logon logic is in a class of it's own, because the system is supposed to offer different logon mechanisms. Due to server migration issues there was an error occurring. That error dumped the entire trace into the error log, including password info! One method expected the username and password as parameters, hence trace wrote everything faithfully into the error log.

The long term fix here is to refactor said class, instead of using username and password as 2 parameters, for example using a single array parameter containing those 2 values (trace will write out Array for the paramater in such cases). There are also other ways of tackling this issue, but that is an entire different issue.

Anyways. Trace messages are helpful, but in this case were outright harmful.

The lesson I learned, as soon as I noticed that trace output: Sometimes suppressing an error message for the time being is an useful stop gap measure to avoid further harm.

In my opinion I didn't think it is a case of bad class design. The error itself was triggered by an PDOException ( timestamp issue moving from MySQL 5.6 to 5.7 ) that just dumped by PHP default everything into the error log.

In general I do not use the @ operator for all the reasons explained in other comments, but in this case the error log convinced me to do something quick until the problem was properly fixed.

0

If you are using a custom error handling function and wanna suppress an error (probably a known error), use this method. The use of '@' is not a good idea in this context as it will not suppress error if error handler is set.

Write 3 functions and call like this.

# supress error for this statement
supress_error_start();  
$mail_sent = mail($EmailTo, $Subject, $message,$headers);
supress_error_end(); #Don't forgot to call this to restore error.  

function supress_error_start(){
    set_error_handler('nothing');
    error_reporting(0);
}

function supress_error_end(){
    set_error_handler('my_err_handler');
    error_reporting('Set this to a value of your choice');
}

function nothing(){ #Empty function
}

function my_err_handler('arguments will come here'){
      //Your own error handling routines will come here
}
sth
  • 200,334
  • 49
  • 262
  • 354
Sumesh
  • 1
0

I have what I think is a valid use-case for error suppression using @.

I have two systems, one running PHP 5.6.something and another running PHP 7.3.something. I want a script which will run properly on both of them, but some stuff didn't exist back in PHP 5.6, so I'm using polyfills like random_compat.

It's always best to use the built-in functions, so I have code that looks like this:

if(function_exists("random_bytes")) {
    $bytes = random_bytes(32);
} else {
    @include "random_compat/random.php"; // Suppress warnings+errors
    if(function_exists("random_bytes")) {
        $bytes = random_bytes(32);
    } else if(function_exists('openssl_random_pseudo_bytes')) {
        $bytes = openssl_random_pseudo_bytes(4);
    } else {
        // Boooo! We have to generate crappy randomness
        $bytes = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',64)),0,32);
    }
}

The fallback to the polyfill should never generate any errors or warnings. I'm checking to see that the function exists after attempting to load the polyfill which is all that is necessary. There is even a fallback to the fallback. And a fallback to the fallback to the fallback.

There is no way to avoid a potential error with include (e.g. using file_exists) so the only way to do it is to suppress warnings and check to see if it worked. At least, in this case.

Christopher Schultz
  • 18,184
  • 5
  • 54
  • 70
-1

I use it when trying to load an HTML file for processing as a DOMDocument object. If there are any problems in the HTML... and what website doesn't have at least one... DOMDocument->loadHTMLFile() will throw an error if you don't suppress it with @. This is the only way (perhaps there are better ones) I've ever been successful in creating HTML scrapers in PHP.

Steve Paulo
  • 17,200
  • 2
  • 21
  • 23