How to get error result of unlink

后端 未结 3 1292
北海茫月
北海茫月 2021-02-07 10:41

If a call to unlink() returns false for the specified path, how do you find out what the reason for the failure was (i.e. EISDIR, ENOENT, ELOOP etc.)? PHP 5.x running on redhat

相关标签:
3条回答
  • 2021-02-07 11:14

    This is not possible, i'm afraid. Here's the C code that handles unlink in php 5.3.

    ret = VCWD_UNLINK(url); <-- calls unlink(2)
    if (ret == -1) {
        if (options & REPORT_ERRORS) {
            php_error_docref1(NULL TSRMLS_CC, url, E_WARNING, "%s", strerror(errno));
        }
        return 0;
    }
    

    as you can see, errno is not returned and there's no way to access it later.

    There's already a bugreport about this, but it doesn't seem to draw too much attention. ;)

    See also this discussion

    0 讨论(0)
  • 2021-02-07 11:18

    here's one way

    unlink("/path/that/does/not/exist");
    print_r(error_get_last());
    

    See Error handling for more details

    0 讨论(0)
  • 2021-02-07 11:33

    I don't think it is possible to get back any error code(s) issued by the system. That is maybe down to the fact that PHP is supposed to be portable, and different OS's have different methods of reporting errors.

    You could of course do a exec('rm ....') and get the error level back but that's not very portable, and makes your app depend on exec() rights.

    Otherwise, if you really, really need this, only a very hacky workaround comes to mind: Create a custom error handler function that tries to fetch the reason for the failure from the warning unlink throws - e.g. check for "Permission denied", or just fetch the whole error message.

    Create a wrapper function around unlink that sets and re-sets the error handler. Something like this:

    function my_unlink($file)
     {
         set_error_handler("my_error_handler");
         unlink($file);
         restore_error_handler();
    
     }
    

    you get my drift.

    If anybody knows a better solution - I'd be interested to hear about it, too....

    0 讨论(0)
提交回复
热议问题