Download File From Remote Server in PHP

There are many methods in PHP that helps to download file from remote server. We can use php functions like file_get_content, copy, fsockopen and fopen to download remote files. But in this post I will use curl to download file. Because it is the advanced way to work with remote resources it can download large files with minimum memory uses.

Before download a file we need to find if file is exists, filesize  etc.

function getFileInfo($url){
  $ch = curl_init($url);
  curl_setopt( $ch, CURLOPT_NOBODY, true );
  curl_setopt( $ch, CURLOPT_HEADER, false );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
  curl_setopt( $ch, CURLOPT_MAXREDIRS, 3 );
  curl_exec( $ch );

  $headerInfo = curl_getinfo( $ch );
  curl_close( $ch );

  return $headerInfo;

You need to pass the url of file in getFileInfo function and it will return an array of file information. Now after checking information you can call fileDownload function to download the file.

function fileDownload($url, $destination){
  $fp = fopen ($destination, 'w+');
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, $url );
  curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );

  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
  curl_setopt( $ch, CURLOPT_FILE, $fp );
  curl_exec( $ch );
  curl_close( $ch );
  fclose( $fp );

  if (filesize($path) > 0) return true;

File will be download to destination path sent as a second parameter of the function fileDownload. Like below:

$url = "http://path/toserver/css.css";
$file_path = "uploads/css.css";
$fileInfo = getFileInfo($url);

if($fileInfo['http_code'] == 200 && $fileInfo['download_content_length'] < 1024*1024){
	if(fileDownload($url, $file_path)){
		echo "File dowloaded.";