0

I am trying to save an image file (from a specific URL) inside a folder in my local system. This is my code:

$image_link = $_POST["url"];//Direct link to image
$split_image = pathinfo($image_link);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $image_link);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$response= curl_exec ($ch);
curl_close($ch);
$file_name = "all_backend_stuff/".$split_image['filename'].".".$split_image['extension'];
$file = fopen($file_name , 'w') or die("X_x");
fwrite($file, $response);
fclose($file);
echo $file_name;

Now although the image is being saved, when I try to open it, it shows that the image is corrupted and it's size on disk is 0 B.

How do I resolve this issue?

EDIT: I have also tried this code:

$loc = "all_backend_stuff/".basename($_POST["url"]);
file_put_contents($loc,file_get_contents($_POST["url"]));
echo $loc;

The image downloaded is still corrupted.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Does this answer your question? [Saving image from PHP URL](https://stackoverflow.com/questions/724391/saving-image-from-php-url) – Lenny4 Nov 23 '22 at 19:04
  • @Lenny4 I had done the exact same thing as mentioned in the post referred, please check my code –  Nov 23 '22 at 19:08
  • then can you provide the url in `$_POST["url"]` ? – Lenny4 Nov 23 '22 at 19:12
  • 1
    I used your code exactly (except I changed all_backend_stuff and the input URL) and it worked. I used my own image URL on a remote server and a local images folder. – imvain2 Nov 23 '22 at 19:18
  • You never actually check if curl successfully downloaded the file, you just assume that it did. – Sammitch Nov 23 '22 at 20:19
  • Strangely, it only works when I am running the code in my `local server` –  Nov 24 '22 at 01:57

1 Answers1

0

it shows that the image is corrupted and it's size on disk is 0 B.

These are mutually exclusive. The image is not corrupted, your script failed.

The answer is in your log file.

Most likely your webserver does not have permission to write/read the file but it could be caused by a whole lot of other things.

symcbean
  • 47,736
  • 6
  • 59
  • 94