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

A bowler hat with radio waves behind it

From Layoff to Leadership: Tom Conlon’s Journey to a Prosperous Business

Welcome to Your 2024 Branding Pep Talk

A bowler hat with radio waves behind it

CEO Tom Conlon talks shop on Podcast Marketing Secrets