Using @ to Disable Errors

If you find an error message particularly annoying and you are sure it definitely does not apply to you, PHP has a method for you to silence the message entirely. If you place an at symbol, @, before a function that generates an error, PHP will catch the error and silence it entirely. Consider the following two complete scripts:

    $passwd = fopen("/etc/shadow", "r");
    if (!$passwd) {
            echo "Failed to open /etc/shadow.\n";
    }

    $passwd = @fopen("/etc/passwd", "r");

In script one, fopen() is used to open the /etc/shadow Unix password file, which is inaccessible to everyone but the superuser. If our user isn't running as root, this will fail, but fopen() will also output an error message. We already have code to handle the possibility that the file open failed, so we don't want that error message to be printed. So, the second script shows us using the @ symbol to ignore errors in that function call—if the open fails, nothing will happen. Even if the function doesn't exist for some reason, nothing will happen—it is all suppressed by @.

While there are legitimate uses for suppressing errors in this way, it is not advised, because it usually works in the same way that sweeping dust under a carpet does not make a house any cleaner. If you explicitly wish to have errors suppressed with @, it is strongly advised that you always write your own code to check return values of functions.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.