Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file from server, using PHP Code

Tags:

php

How can I download a file from PHP code from any server?

like image 314
Asghar Avatar asked Mar 17 '26 10:03

Asghar


1 Answers

You can use Curl to download file from web using php

function curl_get_file_contents($URL) {
  $c = curl_init();
  curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($c, CURLOPT_URL, $URL);
  $contents = curl_exec($c);
  $err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
  curl_close($c);
  if ($contents) return $contents;
  else return FALSE;
}

pass url to this function and download contents. alternatively you can use file reader/writer

private function downloadFile ($url, $path) {
  $newfname = $path;
  $file = fopen ($url, "rb");
  if ($file) {
    $newf = fopen ($newfname, "wb");
    if ($newf)
    while(!feof($file)) {
      fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
    }
  }
  if ($file) {
    fclose($file);
  }
  if ($newf) {
    fclose($newf);
  }
} 

from : This stack question

like image 66
Asghar Avatar answered Mar 20 '26 00:03

Asghar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!