Check if file was created

Asked

Viewed 148 times

4

I made a function that creates a file in php, but I need it to return true if all goes well or false if one of the steps has failed. I solved it as follows:

function createFile($path, $nome, $content){
    if (!($fp = fopen($path.$nome,"wb")))
        return false;
    if (!fwrite($fp,$content))
        return false;
    if (!fclose($fp))
        return false;
    return true;
}

There’s a cleaner way to do that?

The problem of using file_exists is that I won’t know if there was a mistake in fwrite for example. I was wondering if there is such a thing as a try()catch() but with mistakes rather than exceptions.

  • The problem of using file_exists is that I won’t know if there was a mistake in fwrite for example. I was wondering if there is such a thing as a try()catch() but with mistakes rather than exceptions.

  • If I do so as you spoke I can be sure that the if will perform the functions in the right order?

  • Well, if it is to lose readability I will leave the way it is for now. I will research on the try()catch()

1 answer

5


Simplifying

function createFile($path, $nome, $content){
    return file_put_contents($path.$nome, $content);
}

The function file_put_contents() boolean returns false in case of error. Otherwise it will return the amount of bytes written in the file.

This is basically what returns from the function fwrite(), which requires the return of fopen().

However, it does not mean that it is more performatic because it has fewer codes. Normally fopen(), fwrite() and fclose() cost less. However, for a single process it is a derisory cost difference.

If you want to keep the question code and give more consistency, you could add a fourth conditional by checking the Resource:

function createFile($path, $nome, $content){
    if (!($fp = fopen($path.$nome,"wb")))
        return false;
    if (!fwrite($fp,$content))
        return false;
    if (!fclose($fp))
        return false;
    if (!is_resource($fp))
        return false;
    return true;
}

But in this case it is something somewhat unusual. It can happen in specific environments where the fclose() returns true and Resource is still active. In this case the function is_resource() may be useful.

The function file_put_contents() simplifies it all. After all, the result will be the same.

Also note that the name of the function you created is createFile(), however there are several operations that can return different results that may not necessarily be related to what the function nomenclature says "create file".

If you want a meticulous return, you could create an array containing the return of each function, because a situation that can occur is the file being created and the contents being recorded correctly and just fail in the fclose(). But as it stands, a flaw in the fclose() would return false and you don’t know where the value came from false.

You could implement something like this:

function createFile($path, $nome, $content){
    $rs = array(
        'fopen' => null,
        'fwrite' => null,
        'fclose' => null
    );
    if (($rs['fopen'] = fopen($path.$nome, 'wb')) !== false) {
        $rs['fwrite'] = fwrite($rs['fopen'], $content);

        // Invoque fclose() independente do resultado de fwrite().
        $rs['fclose'] = fclose($fp);
    }
    return $rs;
}

Note that fclose() is invoked independent of the return of fwrite(). That’s because even if fwrite() fail the fopen() will remain open. In the original version of the question this does not happen. You have a small Leak.

But I would still suggest changing the function name as it is not only creating a file. It is also inserting data. For a createfile, the ideal would also be to check if the directory is a valid path before even invoking fopen(). Giving more consistency to the function. It may be the case to think of OOP to better organize and avoid this "spaghetti" codes.

If you ask me if I do this in real life. No, I don’t. I just apply the file_put_contents() to be happy. Because in most cases it does not need so much complication. Except, of course, for cases where it really requires a real need to create a "highly" consistent routine.

  • 2

    +1, was very objective, and mentioned several important points in a very succinct way, without excess of parallel information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.