Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

designheroes's avatar

Storing image file retrieved from external url

Im retrieving images from an URL and i can't seem to use the build in store() function with the format i get the file in what could i use that works with the store function instead of the usual form posted file?

0 likes
10 replies
designheroes's avatar

Yea i know i just dont know how to save the "retrieved" file when its not submitted by a form.

designheroes's avatar

Works perfect, thanks! Didn't know you could use that class :)

eXist73's avatar

I'm generating Illuminate\Http\UploadedFile from urls, but this helped me get there. Heres my code for anything interested:

$info = pathinfo($url);
$contents = file_get_contents($url);
$file = '/tmp/' . $info['basename'];
file_put_contents($file, $contents);
$uploaded_file = new UploadedFile($file, $info['basename']);

Then I can run it through my controller logic the same way as if someone on my site uploaded it.

20 likes
kalesh13's avatar

@EXIST73 - This doesn't work now. Laravel has updated the UploadedFile class to accept files that are actually present in the PHP global variable $_FILES. Is there any alternative to this?

eXist73's avatar

@kalesh13

I just tested the following code on laravel version 5.8.14:

$url = 'https://pay.google.com/about/static/images/social/og_image.jpg';
$info = pathinfo($url);
$contents = file_get_contents($url);
$file = '/tmp/' . $info['basename'];
file_put_contents($file, $contents);
$uploaded_file = new UploadedFile($file, $info['basename']);
dd($uploaded_file);
        

And the result can be seen here: https://i.gyazo.com/03b6cd0ea9e5248b1cf2bfcf33ae348c.png

It seems Laravel 5.8.14 seems to work. Was there another version of Laravel this was giving you trouble with?

1 like
rockyxcoded's avatar

@docmojoman That is not true. It only defaults to "application/octet-stream" when it's not manually provided, which is actually not a big deal.

The SplFileObject Library can handle the mimetype for you.

Please or to participate in this conversation.