Loading…

How to download files from an external server with code in PHP?

 

We can do it by various methods, If you have allow_url_fopen set to true:

  • We can download images or files from an external server  with cURL() But in this case, curl has been enabled on both servers
  • We can also do it by file_put_contents()

Example

                                        

$ch = curl_init();
$source = "http://abc.com/logo.jpg";
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "/images/newlogo.jpg";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);

/*-------This is another way to do it-------*/

$url = 'http://abc.com/logo.jpg';
$img = '/images/flower.jpg';
file_put_contents($img, file_get_contents($url));

Suggest An Answer

No suggestions avaliable!

Latest post from PHP interview questions

Ask Question