Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel and AWS PHP SDK - Unable to delete a local file after it was uploaded to S3

I am trying to delete a file from a local directory right after I have uploaded it to AWS S3. When I run it on Vagrant I get an error = Text-file:busy, and when I run it on xampp I get the error :permission denied. For some reason the AWS S3 PutObject method is not releasing the file handle. I have tried to unset the s3 object but that didn't work.

Here is the code:

    $tempName = public_path().'/path/to/file'

    //Initialize AWS
    $s3 = AWS::createClient('s3');


    //Upload image to AWS

    try {
        $reponse = $s3->putObject(array(
            'Bucket'       => 'zotamoda',
            'Key'          => $productImage->image_folder."/".$productImage->image_name,
            'SourceFile'   => $tempName,
            'ACL'          => 'public-read',
        ));
    } catch (S3Exception $e) {
        // The AWS error code (e.g., )
        echo $e->getAwsErrorCode() . "\n";
        // The bucket couldn't be created
        echo $e->getMessage() . "\n";
    }


    //Delete image from temporary location
    unlink($tempName);
like image 957
Oren Reuveni Avatar asked Sep 03 '15 20:09

Oren Reuveni


People also ask

How do I delete files from my AWS S3?

If you no longer need to store the file you've uploaded to your Amazon S3 bucket, you can delete it. Within your S3 bucket, select the file that you want to delete, choose Actions, and then choose Delete. In the confirmation message, choose OK.

How can I read S3 file in PHP?

php'; $s3 = new Aws\S3\S3Client([ 'region' => 'your region', 'version' => 'latest', 'credentials' => [ 'key' => "Your Key Id", 'secret' => "Your secret access key", ] ]); // Send a PutObject request and get the result object.

What happens to an object when we delete it from Amazon S3?

If the version ID maps to a specific object version, Amazon S3 deletes the specific version of the object. If the version ID maps to the delete marker of that object, Amazon S3 deletes the delete marker. This makes the object reappear in your bucket.


1 Answers

You could try:

Storage::disk('s3')->put($productImage->image_folder."/".$productImage->image_name, file_get_contents($tempName), 'public');
unlink($tempName);

or, assuming that $tempName is relative to your project root:

Storage::disk('local')->delete($tempName)
like image 52
Kevin Lee Avatar answered Sep 27 '22 22:09

Kevin Lee