May 9, 2012

copy() not working from url to folder in php

Question by Jay66online

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

Answer by Michael Berkowski

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

Answer by Starx

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!