PHP unlink() handling the exception

前端 未结 7 1104
南旧
南旧 2020-12-15 15:48

Well, I have been wondering if I can handle the unlink() function properly. I dont want the unlink() function to throw some nasty error if it is un

7条回答
  •  隐瞒了意图╮
    2020-12-15 16:25

    This method may seem strange but I believe it is the most foolproof one, it accounts for "race conditions".

    • mkdir-race-condition
    • file_put_contents-race-condition

    is_file

    if(is_file($file) && @unlink($file)){
        // delete success
    } else if (is_file ($file)) {
        // unlink failed.
        // you would have got an error if it wasn't suppressed
    } else {
      // file doesn't exist
    }
    

    Why?

    Firstly is_file is the correct method to check if a FILE exists not file_exists. file_exists checks for both directories and files so may return the TRUE for a directory with the same filename, you cannot remove a directory with unlink and doing so will throw an error.

    Checking a file exists(is_file) before you unlink is the correct/best way to delete a file.

    if(is_file($file) && unlink($file)){
    

    But it is not a foolproof method as it is common for a file to be deleted in the small window between the is_file check and the unlink. I have experianced this several times when a caching method uses the filesystem.

    But it is best method available.

    So you can do everything right and still get an error!

    Well at least the error tells you if it fails....well actually you can tell if it fails without the error

    unlink

    Returns TRUE on success or FALSE on failure.

    If you have coded it correctly and can differentiate between a success and failed unlink then YES suppress the error, it does not benifit you or your code.

    Whether the error is suppressed or not, This is the best method i can think of to prevent it from happening. By reducing the time between the check and the delete you will reduce the likeliness of it throwing an error.

    EDIT: updated link URLs

提交回复
热议问题