Suppressing PHP warnings for specific functions using the @ ‘at’ symbol

By North Street, A Creative Studio

Some PHP functions, return an error rather than gracefully exit.

Lets take the  file_get_contents() function as an example:

$contents = file_get_contents('/path/to/file.html');

If ‘file.html’ doesn’t exit, then it will return something similar to the following:

<b>Warning</b>:  file_get_contents(path/to/file.html): failed to open stream: No such file or directory in <b>/Users/user/Documents/file.php</b> on line <b>13</b><br />

This is of course, problematic as we’re saving the return value into the $content variable to be output later!

The solution? The magic @ symbol. Simply append it do the front of the function, and warnings are suppressed:

$contents = @file_get_contents('/path/to/file.html');

That’s it! Now if ‘file.html’ doesn’t exist, $contents will simply be empty, which we can check for.



About north street

We engineer the thoughtful transformation of great organizations. Our proven process helps us understand what your competitors are doing right — and wrong. Want to learn more? Let’s chat.

More Notes

Team Spotlight: Matt Potter, Web Designer

Postcards from Puerto Rico: North Street Retreat ’22

We’re Hiring: Marketing Coordinator