Open In App

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

Last Updated : 27 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

PHP provides many inbuilt variables or functions to perform this kind of operation. One of them is file_get_contents to download the files from the external server using PHP.

file_get_contents() Function Parameters:

  • $path: It declares the path of the file which we are going to fetch.
  • $include_path: This is a binary parameter, set 1 to find the file in the included path.
  • $context: It specifies how we change the modes of the filehandle.
  • $start: It is the starting line to fetch.
  • $max_length: It specifies the max length of the file.

In this, we are going to understand how to download the files and how to download the content of the particular page from the external server. 

Example 1: In this, we see how to download the file using the file_get_contents() method.

PHP




<?php
    
    $URL
        
    $file = basename($URL);
      
    $success = file_put_contents($file, file_get_contents($URL));
      
    if ($success) {
        echo "File downloaded successfully from the server ";
    }
    else {
        echo "File downloading failed.";
    }
?>


Output:

Example 2: In this, we understand how to download the content from the external server. We set the URL in the variable in which we want to fetch the content. We open a file in write mode and then fetch the content using the cURL method and store the data in a file.

PHP




<?php
  
      $destination_file = "gfg.html";
  
      $fp = fopen($destination_file, "w+");
  
      $ch = curl_init();
        
    curl_setopt_array($ch, array(
          CURLOPT_URL=>$url, CURLOPT_FILE=>$fp ));
  
      $res = curl_exec($ch);
  
      echo "File is downloaded ..!!";
      curl_close($ch);
      fclose($fp);
?>


Output:

Example 3: In this, we are using cURL which is also called as client’s URL. We initialize the file URL and store it in the variable. We specify the file name to store the file, then open the file in w+ mode. By using cURL we first transfer the file and then execute the session. After the file is downloaded we close the session as well as the file.

PHP




<?php
  
      $file_url
  
      $destination_path = "download3.png";
      $fp = fopen($destination_path, "w+");               
  
      $ch = curl_init($file_url);
      curl_setopt($ch, CURLOPT_FILE, $fp);
      curl_exec($ch);
  
      $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close($ch);
      fclose($fp);
  
      if($st_code == 200)
          echo 'File downloaded successfully from the server';
      else
          echo 'Error occur';
?>


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads