How to download an image on device from a direct URL using PHP?
Get the solution ↓↓↓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!
Answer
Solution:
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;
?>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: using $this when not in object context laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.