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

15,396

Solution 1

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.

Solution 2

Use error_get_last() to catch the (supressed) errors in php:

$f = @fopen("x", "r") or die(print_r(error_get_last(),true));
Share:
15,396
puk
Author by

puk

Updated on July 18, 2022

Comments

  • puk
    puk almost 2 years

    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.

  • puk
    puk over 12 years
    Is there a proper way to propagate exceptions back to the client? Right now I am just printing/echoing these.
  • hakre
    hakre over 12 years
    @puk: That's depends how you design your application. It can be just fitting to give back a message, some want to display javascript popups, others want to display an error page and so on and so forth. I think the most important part first is, that you have one useful error message for the user, and one technically insightful error message for the developer, e.g. into an application error log.
  • puk
    puk over 12 years
    would this error be displayed client side, serverside, or does it depend on 'how you design your application'?
  • mpartel
    mpartel over 12 years
    You choose where and how you want to show your errors. Often people show a generic "something went wrong" to the user (except in development mode) and log and/or e-mail the actual error. But don't overcomplicate things prematurely :)
  • puk
    puk over 12 years
    What is the purpose of the '@' here, I have never seen that before.
  • Raul
    Raul over 3 years
    @puk @ symbol is the error control operator. It suppresses any errors emitted by that function. In the end, this means that if the function fails, you won’t see any errors related to it on screen or in your logs. This is a poor practice and should be avoided. You can always set a custom error handler to catch errors.