PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

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

 March 01, 2022     amazon-s3, amazon-web-services, laravel, laravel-5.1, php     No comments   

Issue

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);

Solution

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)


Answered By - Kevin Lee
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing