1

I am trying to copy file from a url to a folder in my system using php

<?php $image = "http://l.yimg.com/t/frontpage/10-facts-slideshow-080512-630-01.jpg";
if (!copy($image, "localfolder/mainPic1.png")) {
echo "FAILED";
}else{echo "DONE";}

it always end up with "Failed"

  • All permissions are set to the localfolder

  • i checked the phpinfo and found that allow_url_fopen =Off

as it is a shared server i do not have any control over the php settings . please can you suggest an alternative.

Thanks, Jay

COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
Jay66online
  • 69
  • 1
  • 2
  • 10
  • Here is the solution similar to our question http://stackoverflow.com/questions/6306935/php-copy-image-to-my-server-direct-from-url – Rajan Rawal May 09 '12 at 05:08

2 Answers2

1

If allow_url_fopen is off and you cannot enable it, you will need to use curl to retrieve the file and save it locally.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://l.yimg.com/t/frontpage/10-facts-slideshow-080512-630-01.jpg");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$imgdata = curl_exec($ch);

// Save to disk
file_put_contents("localfolder/mainPic1.png", $imgdata);
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • ok, i am aware of Curl and fairly know how to use it, i think even using curl i can only fetch the url's of the images? and again i will be back to where i started of copying from url again? please correct me if i am incorrect – Jay66online May 09 '12 at 02:58
  • @Jay66online Not sure what you mean by _only fetch the urls of images_. curl will fetch the image data into the returned variable. – Michael Berkowski May 09 '12 at 02:59
  • @Jay66online I tested the code above, and it will correctly retrieve and save your image URL to a local file. – Michael Berkowski May 09 '12 at 03:03
  • i tried the above code it works quiet good until i checked the size of the file it is saved is 0kb :( when i did an echo ''; it dint show up the file that's when i checked the size – Jay66online May 09 '12 at 03:08
  • hey Michael , i just modified the contents of CURL (pasted above) and it worked !! Thanks a tonne – Jay66online May 09 '12 at 03:19
0

Yes, allow_url_fopen have to ON for this.

allow_url_fopen = On

Even if you are allowed to modify php.ini on your shared server. Create a php.ini and keep the value allow_url_fopen = On in the root folder. It generally overrides the default settings.

Starx
  • 77,474
  • 47
  • 185
  • 261