Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When file_put_contents fails if the directory is full, a file with size 0 is created. How to avoid that?

When the tmp directory is full, file_put_contents returns FALSE but the file is created with size of 0. file_put_contents should either complete the creation of the file or have no effect at all. For example:

$data = 'somedata';
$temp_name = '/tmp/myfile';
if (file_put_contents($temp_name, $data) === FALSE) {
    // the message print that the file could not be created.
    print 'The file could not be created.';
}

But when I go to the tmp directory, I can find the file "myfile" created in the directory with size 0. This makes it difficult to maintain. The file should not be created and I would like to see a message or warning the the tmp directory is full. Am I missing anything? And is this normal behaviors?

like image 628
awm Avatar asked Jan 04 '13 21:01

awm


2 Answers

You are probably missing that if you do the error messages, you need to take care of that scenario, too:

$data      = 'somedata';
$temp_name = '/tmp/myfile';

$success = file_put_contents($temp_name, $data);
if ($success === FALSE)
{
    $exists  = is_file($temp_name);
    if ($exists === FALSE) {
        print 'The file could not be created.';
    } else {
        print 'The file was created but '.
              'it could not be written to it without an error.';
    }
}

This will also allow you to deal with it, like cleaning up if the transaction to write to the temporary file failed, to reset the system back into the state like before.

like image 167
hakre Avatar answered Nov 12 '22 19:11

hakre


The problem is that file_put_contents will not necessarily return a boolean value and therefore your condition may not be appropriate you could try:

if(!file_put_contents($temp_name, $data)){
    print 'The file could not be created.';
    if(file_exists ($temp_name))
        unlink($temp_name);
}
like image 42
Ronald Avatar answered Nov 12 '22 21:11

Ronald