Skip to content
Advertisement

How to download an image on device from a direct URL using PHP?

This might seem a repeated question, but trust me I have read many topics here, none of the solutions worked for me ????

What I particularly aim to do is, let’s say I have this image URL – https://catfriendly.com/wp-content/uploads/2019/06/AdobeStock_53119595.jpeg, and I want to Download it on my user’s phone. I would redirect the user to URL when he/she clicks the download button, and then the URL’s image would be downloaded on the user’s phone. Is this possible to do?

I’ve tried this code,

<?php>
$url = 'https://catfriendly.com/wp-content/uploads/2019/06/AdobeStock_53119595.jpeg';
$img = '/Downloads/one.jpeg';
file_put_contents($img, file_get_contents($url));
?>

What’s wrong in this one? Thanks!

Advertisement

Answer

I think the problem with your code is that it is executed on your server, but not on the user’s phone.

So you have to modify your code a little:

<?php
$url = 'https://catfriendly.com/wp-content/uploads/2019/06/AdobeStock_53119595.jpeg';

// leave this out because it only stores the image on the server
// $img = '/Downloads/one.jpeg';
// file_put_contents($img, file_get_contents($url));

// get the image content:
$img_content = file_get_contents($url);

// tell the client that you will send an image
header('Content-Type: image/jpeg');

// tell the client not to display the image, but to download it
header('Content-Disposition: attachment; filename="YourFilenameHere.jpg"');

// finally, output the image
echo $img_content;

?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement