PHP: The @ Operator

I’ve seen some confusion online lately about the purpose of the “@” operator in PHP. Let’s figure out exactly what the “at operator” does.

PHP holds your hand with error reporting during development by printing error messages to the user’s browser automatically when something goes wrong. This often looks something like this:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host ‘woopsy.example.com’ (1) in errors.php on line 3

The code that created this warning looks like this:

mysql_connect( "woopsy.example.com" );

Pretty simple — I tried to connect to a non-existent MySQL server using a mistaken hostname. This is handy, but I usually don’t like these kinds of errors to show up when a user browses my site. We can make the error go away by prepending a “@” on the front of the call to mysql_connect(), like this:

@mysql_connect( "woopsy.example.com" );

This gets rid of the warning message we saw earlier, but now we have no way of knowing whether mysql_connect() was actually able to connect or not. To fix that, we need to check the return value. According to the mysql_connect() documentation, the function returns a MySQL link identifier on success and FALSE on failure. So, let’s do this:

$db = @mysql_connect( "woopsy.example.com" );
if( $db === false )
{
   echo "Could not connect to server.";
   exit();
} 

The lesson to take away from this is that the “@” operator suppresses error messages, not return values. You can read more about the operator at the PHP Error Control Operator documentation page.

For the motivated reader, the “@” operatore has many more applications. You can use it to suppress errors in include files and even bad array indexes.

The best way to deal with errors, however, is to use your own error handling function by calling set_error_handler() . This way, you can get notified whenever an error occurs, and you can even be told the error number, message, file, and line number. This way you can log it or even present a link for users to report the bug. It’s very handy, and a great way to find and fix bugs without requiring too much user inconvenience.

The phpLDAPadmin project has an excellent implementation of an error handler, which can be viewed here. Search that page for pla_error_handler. It reports lots of versions (ie, the web server and PHP version), the exact error message, and even some PHP settings. It proved very useful for users to report bugs, since they could just copy/paste the output on the SourceForge bug tracker. ‘

This leads me to my final comment. I’ve already mentioned that the best way to handle errors in PHP is to implement your own error handler and call set_error_handler(). In this function, you should log all errors, and then only display a message for those that happen without the “@” operator present. In other words, you should do something like this:

function my_error_handler( $errno, $errstr, $file, $lineno )
{
   my_log_msg( "Error $errno: $errstr in file $file on line $lineno" );

   if( 0 == ini_get( "error_reporting" ) || 0 == error_reporting() )
      return;

   // Display an error message of some kind
}

Any now my final comment: I use error_reporting() in all my PHP applications to set the strictest error reporting possible like so:

error_reporting( E_STRICT );

You may not want such strict error reporting in your application, so choose from the available error levels. This will give you all kinds of error messages, but it will help you bullet-proof your code in a jiffy.

Enjoy your error reporting!

15 comments to “PHP: The @ Operator”

You can leave a reply or Trackback this post.
  1. http://Lonnie%20Olson says: -#1

    Thanks for the article.

    One additional note: When use your own error handler, it is very useful to check the return value of error_reporting(). This will return 0, if the “@” operator was used to suppress errors.

  2. http://Daisy%20P. says: -#1

    thank you for your brief explanations about the @ operator. it is very useful and understandable for me..

  3. Hey,

    thanks for your article. I was about to go crazy searching for it. Asking Mr. G00gle would not help using the “@” symbol ;-)”.

    BTW, @ is a cool feature of PHP

    cheers
    Dirk

  4. http://venkatesh says: -#1

    Hai,
    Thank you for this article. It is very helpful for me i was not knowing this @ symbol used for error handling. Thanks thanks a lot.
    @is very cool guys.

  5. http://unknown says: -#1

    The @-Operator is really slow.
    And do NOT use it for assignments like
    @$var = $_POST[‘var’];
    please use
    $var = isset($_POST[‘var’])?$_POST[‘var’]:’my default value’;
    PS: Always use error_reporting(E_ALL) and respect the warnings and notices.

  6. http://name says: -#1

    thank you. what is the & operator? i saw this in php manual in array section.

  7. The & operator is used when you pass a variable to a function to tell PHP to pass it by reference instead of passing it by value (copy on write), like this:

    $var = “foo”;
    some_fiunction(&$var);

    Unlike C++, in PHP the caller chooses when to pass by value and when to pass by reference. In C++, the function writer indicates this with the & character in the function signature.

  8. http://Andrew says: -#1

    @unknown (ironic huh)

    you can always do this:
    $str =@ $_POST[“something”];

  9. http://rejani says: -#1

    Thanks for the crystal clear explanation of @.
    It is very useful.

  10. http://Mostafa says: -#1

    Very helpful
    I didnt find @ operator explanation easily.

  11. I came here only seeking information about PHP @ operator and learned a bit about error handling in here too.

    This is a very good article.

  12. I’m not sure if this is a legitimate use of `@` but I’ve used it with PHP 5.2.6 and WAMP in a @require_once(“SomeScriptWithEchos.php”); statement to keep the echos from writing to the output buffer and stopping a redirect from happening. That way I can run “SomeScriptWithEchos.php” directly for maintainence or include it in automated scripts inside out application.

    I will note it didn’t work on our production site running php 5.2.(>6) and I had to comment out the echo statements in “SomeScriptWithEchos.php”. I am curious if this is an ok use or am I making a feature out of a bug?

  13. SWiT: I would probably suggest that you are making a feature out of a bug by using @ to suppress all output with require_once(). A better approach would probably be to:

    1. Refactor the code in SomeScriptWithEchos.php to be more of a library that *can* produce output when asked, but doesn’t *have* to produce output.

    2. Or use output buffering to suppress output instead:
    http://php.net/manual/en/book.outcontrol.php

  14. Thank you! I always used to set error_reporting level to zero to suppress errors.

  15. http://Sejanus says: -#1

    the correct way is to write your own custom error handler (which is rather easy and faster than it sounds) and choose what and when errors to show, what to log (if needed), etc. @ always and I mean always is bad. Wait till you need to debug the code which is already in production with @ all over the place.