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

docmojoman's avatar

Download and store a file from an external api to my server

I am creating an app that relies on gathering content from an external api. The api provides links to a series of images that I need to download and store on my server.

The following solution appears to have worked years ago, found here:

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

Apparently, UploadedFile requires the data to be included in the global $_FILES array in order to gain access to all the helpful tools like store() and storeAs().

Any suggestions?

0 likes
7 replies
jlrdw's avatar

Either use their image link, or just like most do, right click image, and save as .....

But ensure it's okay to have image on your server. It usually is, i.e., like Paypal.

If some images have build in links, the api should have exact instructions of "what to do".

Again like a Paypal image.... Sorry if I misunderstood question.

docmojoman's avatar

The api provides the image links, but I'm building this app to automate the downloading and saving of these images.

jlrdw's avatar

A url is not a path. See https://laravel.com/docs/6.x/filesystem#retrieving-files

A path has to be used. I am not sure if the laravel helpers will work, you may need to supply path manually.

Again, their api should have full instructions.

<?php
$basedir = '/Bitnami/wampstack-7.3.1-0/apache2/laravel60up/storage/app/upload';

$imagedir = $_GET['dir'];
$image = $_GET['img'];

$file = $basedir.'/'.$imagedir.'/'.$image;

header('Content-Type: image/jpeg');
ob_clean();
readfile($file);
exit(0);

?> 

Just example,

$file = $basedir.'/'.$imagedir.'/'.$image;    <----- PATH not url
Talinon's avatar

@docmojoman I've had a quick look at the code base, and I don't see what would be preventing you from using it?

What version of Laravel are you using? And what does dd($uploaded_file) export?

As for your response in that referenced thread, I don't think a mime type of application/octet-stream means failure, it's just the default setting if you don't provide one within the constructor.

Can you not just use Storage::put()? What tools are you trying to gain access to via UploadedFile that is making you go thru this trouble?

Snapey's avatar

You cant use the uploaded file object because that is for things that are posted to your server, but you can just getFileContents and write it to storage (as @talinon said earlier)

docmojoman's avatar

@talinon & @jlrdw - thanks for your replies it turns out, that I need to get a better handle on Laravel's file handling.

Please or to participate in this conversation.