phplaravelfilefile-upload

Save an image from an external URL in Laravel


I want to save an image in my S3 using an URL.

Here is my code:

public function uploadFromUrl(string $url, string $path, string $filename): string
    {
        $contents = file_get_contents($url);
        $storage_disk = 'local' === config('app.env') ? 'public' : 's3';
        Storage::disk($storage_disk)->putFile($filename, $contents);

        if ('production' === config('app.env')) {
            $url = Storage::disk($storage_disk)->url($path.'/'.$filename);

            return str_replace(config('filesystems.disks.s3.url'), config('filesystems.disks.s3.cloudfront_url'), $url);
        }

        return Storage::disk($storage_disk)->url($path.'/'.$filename);
    }

Here is the url (example): https://scontent-lhr8-1.cdninstagram.com/v/t51.2885-15/67382942_125369622063864_5790726279801419518_n.jpg?_nc_cat=106&ccb=1-7&_nc_sid=8ae9d6&_nc_ohc=pN7mDdfhZ5oAX_5m3qK&_nc_ht=scontent-lhr8-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT-sSvo7gKRJbm_xWo0Giayjxt9jDmX7SnOKc0ZuoVW44A&oe=62BEB3B2

I receive the follow error:

code: "INVALID_ARGUMENT_EXCEPTION" message: "Malformed UTF-8 characters, possibly incorrectly encoded"


Solution

  • Use put() instead of putFile()

    Storage::disk($storage_disk)->put($filename, $contents);
    

    put()

    public function put($path, $contents, $lock = false)
    {
         return file_put_contents($path, $contents, $lock ? LOCK_EX : 0);
    }