1

I want to check wether unlink returns true or false.

Currently I tried this:

if(!unlink("$directory/$file"))
{
     echo "works not";
}
else
{
     echo "works";
}

I get not output, I just get this message:

unlink("path"...VTS_01_1.VOB): Permission denied

But it does not work, any ideas?

J.Alan
  • 85
  • 1
  • 2
  • 12
  • And what you got here as output? – Alive to die - Anant Feb 10 '17 at 16:20
  • I got nothing, I just get this message: `unlink("path"...VTS_01_1.VOB): Permission denied` – J.Alan Feb 10 '17 at 16:21
  • I intentionally have that folder/file open to catch the error and show a suitable message to this issue, there is no permission error in that case it just shows me the error because I have the folder/file opened. – J.Alan Feb 10 '17 at 16:24
  • Possible duplicate of [PHP unlink() handling the exception](http://stackoverflow.com/questions/15318230/php-unlink-handling-the-exception) – Felippe Duarte Feb 10 '17 at 16:25
  • Well, something *should* be output here one way or the other… Can you try to do literally *anything else* besides `echo`, to rule out that for whatever bizarre reason there's some issue with outputting to `stdout`? Throw an exception instead, write to some other file, play a sound or something, just to see that it *is* progressing into either `if` or `else`. – deceze Feb 10 '17 at 16:31
  • I put an exception into both but I did not get anything – J.Alan Feb 10 '17 at 16:36
  • Not exactly same but you will get some help (bare me if not):- http://stackoverflow.com/questions/16975998/how-can-you-catch-a-permission-denied-error-when-using-fopen-in-php-without-us – Alive to die - Anant Feb 10 '17 at 16:47

1 Answers1

3

You may use is_writable function before trying to unlink:

if( ! @is_writable( "$directory/$file" ) ) {
     echo "works not";
}
else {
    unlink( "$directory/$file" );
    echo "works";
}

is_writable function will show warning (if error is displayed according to configuration) if it fails, so use @ to suppress the error as shown in the CODE above.

Having said that, your CODE is not wrong either, even with your CODE along with the Error, you should've got works not as output as well. If you don't get it, that most likely mean in your CODE an error handler is set somewhere & the handler is ending the execution by exit or die.

For example, the following CODE will only generate Error, no output (if "$directory/$file" is not writable):

function handle_error( $errno, $errstr, $errfile, $errline ) {
    die( $errstr );
}
set_error_handler( 'handle_error' );

// Note: since error handler ends execution with die
// even suppressing warning with @unlink will not give you
// any output other than the error
if( ! @unlink( "$directory/$file" ) ) {
     echo "works not";
}
else {
     echo "works";
}

So check for either set_error_handler or set_exception_handler, see if they are stopping the execution. Output buffering may also be the cause.

Fayaz
  • 1,081
  • 11
  • 20