Php - unlink throws error: resource is temporarily unavailable

Here is the code snippet:

public function uploadPhoto(){
    $filename = '../storage/temp/image.jpg';  
    file_put_contents($filename,file_get_contents('http://example.com/image.jpg'));
    $photoService->uploadPhoto($filename);
    echo("If file exists: ".file_exists($filename));
    unlink($filename);
}

I am trying to do the following:

  • Get the photo from the URL and save it in a temporary folder on my server. It works great. An image file is created and echoed If file exists: 1when echo("If file exists: ".file_exists('../storage/temp/image.jpg'));.
  • Pass this file to another function that uploads the file to the Amazon s3 trash. The file is stored in my s3 statement.
  • Delete the photo saved in the temp folder. This does not work! I get an error message:

unlink (../storage/temp/image.jpg): the resource is temporarily unavailable

If I use rename($filename,'../storage/temp/renimage.jpg');instead unlink($filename);, I get an error:

rename (../storage/temp/image.jpg,../storage/temp/renimage.jpg): , . (: 32)

$photoService->uploadPhoto($filename);, .

, , - ? .

, ! .

+6
5

.

, $photoService - ... $photoService, - ( $photoService):

[...]
echo("If file exists: ".file_exists($filename));
unset($photoService);
unlink($filename);
}

unset() /, "" ( wharever it) .

+2

. S3, , , . "" putObject:

$fileContent = file_get_contents($filepath);
$result = $s3->putObject(array(
    'Bucket'       => $bucket,
    'Key'          => $folderPath,
    'Body'         => $fileContent,
     //'SourceFile'   => $filepath,
    'ContentType'  => 'text/csv',
    'ACL'          => 'public-read'
));

: AWS S3?

+1

, , , " " "".

PHP- , . unlink() , .

: ( , ) @, (, beinf), :

$gone = false;
for ($trial=0; $trial<10; $trial++) {
    if ($gone = @unlink($filename)) {
        break;
    }
    // Wait a short time
    usleep(250000);
    // Maybe a concurrent script has deleted the file in the meantime
    clearstatcache();
    if (!file_exists($filename)) {
        $gone = true;
        break;
    }
}
if (!$gone) {
    trigger_error('Warning: Could not delete file '.htmlspecialchars($filename), E_USER_WARNING);
}

, " " file_put_contents(). , .

/ , @ ob_start(), .

+1

:

gc_collect_cycles();
unlink($file);

! amazon S3 .

: https://github.com/aws/aws-sdk-php/issues/841

GuzzleHttp\Stream , __destruct. , , , , PHP , , . gc_collect_cycles __destruct .

:)

0

The unlink method returns bool, so you can build a loop with some wait () and limit the number of attempts to wait for processes to complete.

Additionally, add "@" in the disabled link to hide the access error.

Throw another error / exception if the number of attempts is reached.

-2
source

Source: https://habr.com/ru/post/1673521/


All Articles