phpfileerror-handlingsuphp

Get meaningful information when fopen() fails (PHP/suPHP)


How do I get something more meaningful than 'FALSE' when I can't open a file.

$myFile = "/home/user/testFile.txt"; 
$fh = fopen($myFile, 'w') or die("can't open file");

When I use the die statement, can't open file is returned to the client, and it is almost useless. If I remove it, no error is raised. If I return $fh it is FALSE. I tried both local file name and absolute file name. My index.html file is in one of the sub folders of my hole folder. Furthermore, I am using suPHP with the folder I am trying to write to having a permission of 0755 (suPHP requires this for all folders).

How do I figure out why there was a problem, or at least query it before trying to open the file.


Solution

  • fopen should raise an E_WARNING if it fails. See error_get_last or set_error_handler(*) to catch it. Other than that you can use file_exists and is_readable to check whether the file is missing or there's another (probably permission-related) problem.

    (*) I consider it good practice to always set an error handler that turns all PHP errors into exceptions.