Question

I'm trying to debug a huge, antiquated (circa 2001) PHP web service and I'm encountering file open failures. The fopen call is in an included module, the caller is logging that the file could not be opened but no reason is being logged.

The code that actually does the open is:

  // Read the file
  if (!($fp = @fopen($fileName, 'rb'))) {
    $errStr = "Failed to open '{$fileName}' for read.";
    break; // try-block
  }

How can I find out why fopen failed?

Was it helpful?

Solution

Great answers have already been given, about the @ operator, but here's a couple of more informations that could be useful, either to you or someone else :

  • If, for debugging purposes, you need the disable the @ operator, you can install the scream extension -- see also the manual -- which is really useful when you're maintaining some kind of old application not well designed / coded ^^
  • Depending on your PHP configuation (if the track_errors option is activated), you might be able to use $php_errormsg to get the last error message.

Considering this piece of code :

// This file doesn't exist
if (!@fopen('/tmp/non-existant-file.txt', 'r')) {
    var_dump($php_errormsg);
}

// My Apache server doesn't have the right to read this file
if (!@fopen('/tmp/vboxdrv-Module.symvers', 'w')) {
    var_dump($php_errormsg);
}

You would get this :

string 'fopen(/tmp/non-existant-file.txt) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: No such file or directory' (length=129)

string 'fopen(/tmp/vboxdrv-Module.symvers) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: Permission denied' (length=122)

So, real, useful, meaningful, error messages ;-)

OTHER TIPS

Take away the @ sign.

The @ sign suppresses error messages, so it is supressing the error the the function would normally give.

Remove the error suppressor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top