0

I have a function that tries to grab some emails using the imap library. If it can't connect I would like the function to just return without doing anything else.

$imap = imap_open($mailboxPath, $username, $password);
if (!$imap)
  return 0;

This works but I still get a PHP warning message that the connection attempt has failed from a timeout. Can I prevent this warning from being displayed?

Juicy
  • 11,840
  • 35
  • 123
  • 212
  • Using the `OP_SILENT` option flag as described in the docs should prevent it from issuing that E_WARNING. http://us2.php.net/manual/en/function.imap-open.php – Michael Berkowski Oct 05 '13 at 17:59
  • possible duplicate of [Can't silence imap\_open error notices in PHP](http://stackoverflow.com/questions/5422405/cant-silence-imap-open-error-notices-in-php) – Michael Berkowski Oct 05 '13 at 18:01
  • Actually based on a deleted answer in the question I linked, OP_SILENT may not actually work for that purpose and you have to `@` suppress the error :/ – Michael Berkowski Oct 05 '13 at 18:01

2 Answers2

1

You can use set_error_handler() function to define own function responsible for handling different types of PHP errors. If you want to change the way how warnings are handled, your code may look like this:

set_error_handler("warning_handler", E_WARNING);

$imap = imap_open($mailboxPath, $username, $password);
if (!$imap)
  return 0;

function warning_handler($errno, $errstr) { 
// don't display the message, maybe write it to log file
}

If you just want to hide warnings, you can pass an empty anonymous function to set_error_handler():

set_error_handler("warning_handler", function() {});

But in this case you will loose any trace of warnings that may occur in your script.

Jacek Barecki
  • 429
  • 3
  • 7
1

To explicitly supress warnings in php, prefix the function you're calling with @. Try to do this as little as possible, though.

Ivo
  • 5,378
  • 2
  • 18
  • 18
  • Unfortunately, adding @ will suppress all kinds of errors, even fatal errors which terminate script execution. So a simple typo or any other more complicated error can break your script without any notification. – Jacek Barecki Oct 05 '13 at 18:53